* (bug 2118) Added a __LCFIRST__ magic word for forcing the first character of
[lhc/web/wiklou.git] / includes / Parser.php
1 <?php
2 /**
3 * File for Parser and related classes
4 *
5 * @package MediaWiki
6 * @subpackage Parser
7 */
8
9 /** */
10 require_once( 'Sanitizer.php' );
11
12 /**
13 * Update this version number when the ParserOutput format
14 * changes in an incompatible way, so the parser cache
15 * can automatically discard old data.
16 */
17 define( 'MW_PARSER_VERSION', '1.5.0' );
18
19 /**
20 * Variable substitution O(N^2) attack
21 *
22 * Without countermeasures, it would be possible to attack the parser by saving
23 * a page filled with a large number of inclusions of large pages. The size of
24 * the generated page would be proportional to the square of the input size.
25 * Hence, we limit the number of inclusions of any given page, thus bringing any
26 * attack back to O(N).
27 */
28
29 define( 'MAX_INCLUDE_REPEAT', 100 );
30 define( 'MAX_INCLUDE_SIZE', 1000000 ); // 1 Million
31
32 define( 'RLH_FOR_UPDATE', 1 );
33
34 # Allowed values for $mOutputType
35 define( 'OT_HTML', 1 );
36 define( 'OT_WIKI', 2 );
37 define( 'OT_MSG' , 3 );
38
39 # string parameter for extractTags which will cause it
40 # to strip HTML comments in addition to regular
41 # <XML>-style tags. This should not be anything we
42 # may want to use in wikisyntax
43 define( 'STRIP_COMMENTS', 'HTMLCommentStrip' );
44
45 # prefix for escaping, used in two functions at least
46 define( 'UNIQ_PREFIX', 'NaodW29');
47
48 # Constants needed for external link processing
49 define( 'URL_PROTOCOLS', 'http|https|ftp|irc|gopher|news|mailto' );
50 define( 'HTTP_PROTOCOLS', 'http|https' );
51 # Everything except bracket, space, or control characters
52 define( 'EXT_LINK_URL_CLASS', '[^]<>"\\x00-\\x20\\x7F]' );
53 # Including space
54 define( 'EXT_LINK_TEXT_CLASS', '[^\]\\x00-\\x1F\\x7F]' );
55 define( 'EXT_IMAGE_FNAME_CLASS', '[A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]' );
56 define( 'EXT_IMAGE_EXTENSIONS', 'gif|png|jpg|jpeg' );
57 define( 'EXT_LINK_BRACKETED', '/\[(\b('.URL_PROTOCOLS.'):'.EXT_LINK_URL_CLASS.'+) *('.EXT_LINK_TEXT_CLASS.'*?)\]/S' );
58 define( 'EXT_IMAGE_REGEX',
59 '/^('.HTTP_PROTOCOLS.':)'. # Protocol
60 '('.EXT_LINK_URL_CLASS.'+)\\/'. # Hostname and path
61 '('.EXT_IMAGE_FNAME_CLASS.'+)\\.((?i)'.EXT_IMAGE_EXTENSIONS.')$/S' # Filename
62 );
63
64 /**
65 * PHP Parser
66 *
67 * Processes wiki markup
68 *
69 * <pre>
70 * There are three main entry points into the Parser class:
71 * parse()
72 * produces HTML output
73 * preSaveTransform().
74 * produces altered wiki markup.
75 * transformMsg()
76 * performs brace substitution on MediaWiki messages
77 *
78 * Globals used:
79 * objects: $wgLang, $wgLinkCache
80 *
81 * NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
82 *
83 * settings:
84 * $wgUseTex*, $wgUseDynamicDates*, $wgInterwikiMagic*,
85 * $wgNamespacesWithSubpages, $wgAllowExternalImages*,
86 * $wgLocaltimezone
87 *
88 * * only within ParserOptions
89 * </pre>
90 *
91 * @package MediaWiki
92 */
93 class Parser
94 {
95 /**#@+
96 * @access private
97 */
98 # Persistent:
99 var $mTagHooks;
100
101 # Cleared with clearState():
102 var $mOutput, $mAutonumber, $mDTopen, $mStripState = array();
103 var $mVariables, $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
104 var $mInterwikiLinkHolders, $mLinkHolders;
105
106 # Temporary:
107 var $mOptions, $mTitle, $mOutputType,
108 $mTemplates, // cache of already loaded templates, avoids
109 // multiple SQL queries for the same string
110 $mTemplatePath; // stores an unsorted hash of all the templates already loaded
111 // in this path. Used for loop detection.
112
113 /**#@-*/
114
115 /**
116 * Constructor
117 *
118 * @access public
119 */
120 function Parser() {
121 global $wgContLang;
122 $this->mTemplates = array();
123 $this->mTemplatePath = array();
124 $this->mTagHooks = array();
125 $this->clearState();
126 }
127
128 /**
129 * Clear Parser state
130 *
131 * @access private
132 */
133 function clearState() {
134 $this->mOutput = new ParserOutput;
135 $this->mAutonumber = 0;
136 $this->mLastSection = '';
137 $this->mDTopen = false;
138 $this->mVariables = false;
139 $this->mIncludeCount = array();
140 $this->mStripState = array();
141 $this->mArgStack = array();
142 $this->mInPre = false;
143 $this->mInterwikiLinkHolders = array();
144 $this->mLinkHolders = array(
145 'namespaces' => array(),
146 'dbkeys' => array(),
147 'queries' => array(),
148 'texts' => array(),
149 'titles' => array()
150 );
151 }
152
153 /**
154 * First pass--just handle <nowiki> sections, pass the rest off
155 * to internalParse() which does all the real work.
156 *
157 * @access private
158 * @param string $text Text we want to parse
159 * @param Title &$title A title object
160 * @param array $options
161 * @param boolean $linestart
162 * @param boolean $clearState
163 * @return ParserOutput a ParserOutput
164 */
165 function parse( $text, &$title, $options, $linestart = true, $clearState = true ) {
166 global $wgUseTidy, $wgContLang, $wgCapitalLinks;
167 $fname = 'Parser::parse';
168 wfProfileIn( $fname );
169
170 if ( $clearState ) {
171 $this->clearState();
172 }
173
174 $this->mOptions = $options;
175 $this->mTitle =& $title;
176 $this->mOutput->mLcfirstTitle = false;
177 $this->mOutputType = OT_HTML;
178
179 $this->mStripState = NULL;
180
181 //$text = $this->strip( $text, $this->mStripState );
182 // VOODOO MAGIC FIX! Sometimes the above segfaults in PHP5.
183 $x =& $this->mStripState;
184 $text = $this->strip( $text, $x );
185
186 $text = $this->internalParse( $text );
187
188 // if the string __LCFIRST__ (make the first character of the title
189 // lower case) occurs in the HTML, set the mLcfirstTitle to true
190 $mw =& MagicWord::get( MAG_LCFIRST );
191 if( $mw->matchAndRemove( $text ) && $wgCapitalLinks ) {
192 $title->lcfirst();
193 $this->mOutput->mLcfirstTitle = true;
194 }
195
196 $text = $this->unstrip( $text, $this->mStripState );
197
198 # Clean up special characters, only run once, next-to-last before doBlockLevels
199 $fixtags = array(
200 # french spaces, last one Guillemet-left
201 # only if there is something before the space
202 '/(.) (?=\\?|:|;|!|\\302\\273)/' => '\\1&nbsp;\\2',
203 # french spaces, Guillemet-right
204 '/(\\302\\253) /' => '\\1&nbsp;',
205 '/<hr *>/i' => '<hr />',
206 '/<br *>/i' => '<br />',
207 '/<center *>/i' => '<div class="center">',
208 '/<\\/center *>/i' => '</div>',
209 );
210 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
211
212 # only once and last
213 $text = $this->doBlockLevels( $text, $linestart );
214
215 $this->replaceLinkHolders( $text );
216
217 $dashReplace = array(
218 '/ - /' => "&nbsp;&ndash; ", # N dash
219 '/(?<=[\d])-(?=[\d])/' => "&ndash;", # N dash between numbers
220 '/ -- /' => "&nbsp;&mdash; " # M dash
221 );
222 $text = preg_replace( array_keys($dashReplace), array_values($dashReplace), $text );
223
224 # the position of the convert() call should not be changed. it
225 # assumes that the links are all replaces and the only thing left
226 # is the <nowiki> mark.
227 $text = $wgContLang->convert($text);
228 $this->mOutput->setTitleText($wgContLang->getParsedTitle());
229
230 $text = $this->unstripNoWiki( $text, $this->mStripState );
231
232 $text = Sanitizer::normalizeCharReferences( $text );
233 global $wgUseTidy;
234 if ($wgUseTidy) {
235 $text = Parser::tidy($text);
236 }
237
238 $this->mOutput->setText( $text );
239 wfProfileOut( $fname );
240 return $this->mOutput;
241 }
242
243 /**
244 * Get a random string
245 *
246 * @access private
247 * @static
248 */
249 function getRandomString() {
250 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
251 }
252
253 /**
254 * Replaces all occurrences of <$tag>content</$tag> in the text
255 * with a random marker and returns the new text. the output parameter
256 * $content will be an associative array filled with data on the form
257 * $unique_marker => content.
258 *
259 * If $content is already set, the additional entries will be appended
260 * If $tag is set to STRIP_COMMENTS, the function will extract
261 * <!-- HTML comments -->
262 *
263 * @access private
264 * @static
265 */
266 function extractTags($tag, $text, &$content, $uniq_prefix = ''){
267 $rnd = $uniq_prefix . '-' . $tag . Parser::getRandomString();
268 if ( !$content ) {
269 $content = array( );
270 }
271 $n = 1;
272 $stripped = '';
273
274 while ( '' != $text ) {
275 if($tag==STRIP_COMMENTS) {
276 $p = preg_split( '/<!--/', $text, 2 );
277 } else {
278 $p = preg_split( "/<\\s*$tag\\s*>/i", $text, 2 );
279 }
280 $stripped .= $p[0];
281 if ( ( count( $p ) < 2 ) || ( '' == $p[1] ) ) {
282 $text = '';
283 } else {
284 if($tag==STRIP_COMMENTS) {
285 $q = preg_split( '/-->/i', $p[1], 2 );
286 } else {
287 $q = preg_split( "/<\\/\\s*$tag\\s*>/i", $p[1], 2 );
288 }
289 $marker = $rnd . sprintf('%08X', $n++);
290 $content[$marker] = $q[0];
291 $stripped .= $marker;
292 $text = $q[1];
293 }
294 }
295 return $stripped;
296 }
297
298 /**
299 * Strips and renders nowiki, pre, math, hiero
300 * If $render is set, performs necessary rendering operations on plugins
301 * Returns the text, and fills an array with data needed in unstrip()
302 * If the $state is already a valid strip state, it adds to the state
303 *
304 * @param bool $stripcomments when set, HTML comments <!-- like this -->
305 * will be stripped in addition to other tags. This is important
306 * for section editing, where these comments cause confusion when
307 * counting the sections in the wikisource
308 *
309 * @access private
310 */
311 function strip( $text, &$state, $stripcomments = false ) {
312 $render = ($this->mOutputType == OT_HTML);
313 $html_content = array();
314 $nowiki_content = array();
315 $math_content = array();
316 $pre_content = array();
317 $comment_content = array();
318 $ext_content = array();
319 $gallery_content = array();
320
321 # Replace any instances of the placeholders
322 $uniq_prefix = UNIQ_PREFIX;
323 #$text = str_replace( $uniq_prefix, wfHtmlEscapeFirst( $uniq_prefix ), $text );
324
325 # html
326 global $wgRawHtml, $wgWhitelistEdit;
327 if( $wgRawHtml && $wgWhitelistEdit ) {
328 $text = Parser::extractTags('html', $text, $html_content, $uniq_prefix);
329 foreach( $html_content as $marker => $content ) {
330 if ($render ) {
331 # Raw and unchecked for validity.
332 $html_content[$marker] = $content;
333 } else {
334 $html_content[$marker] = '<html>'.$content.'</html>';
335 }
336 }
337 }
338
339 # nowiki
340 $text = Parser::extractTags('nowiki', $text, $nowiki_content, $uniq_prefix);
341 foreach( $nowiki_content as $marker => $content ) {
342 if( $render ){
343 $nowiki_content[$marker] = wfEscapeHTMLTagsOnly( $content );
344 } else {
345 $nowiki_content[$marker] = '<nowiki>'.$content.'</nowiki>';
346 }
347 }
348
349 # math
350 $text = Parser::extractTags('math', $text, $math_content, $uniq_prefix);
351 foreach( $math_content as $marker => $content ){
352 if( $render ) {
353 if( $this->mOptions->getUseTeX() ) {
354 $math_content[$marker] = renderMath( $content );
355 } else {
356 $math_content[$marker] = '&lt;math&gt;'.$content.'&lt;math&gt;';
357 }
358 } else {
359 $math_content[$marker] = '<math>'.$content.'</math>';
360 }
361 }
362
363 # pre
364 $text = Parser::extractTags('pre', $text, $pre_content, $uniq_prefix);
365 foreach( $pre_content as $marker => $content ){
366 if( $render ){
367 $pre_content[$marker] = '<pre>' . wfEscapeHTMLTagsOnly( $content ) . '</pre>';
368 } else {
369 $pre_content[$marker] = '<pre>'.$content.'</pre>';
370 }
371 }
372
373 # gallery
374 $text = Parser::extractTags('gallery', $text, $gallery_content, $uniq_prefix);
375 foreach( $gallery_content as $marker => $content ) {
376 require_once( 'ImageGallery.php' );
377 if ( $render ) {
378 $gallery_content[$marker] = Parser::renderImageGallery( $content );
379 } else {
380 $gallery_content[$marker] = '<gallery>'.$content.'</gallery>';
381 }
382 }
383
384 # Comments
385 if($stripcomments) {
386 $text = Parser::extractTags(STRIP_COMMENTS, $text, $comment_content, $uniq_prefix);
387 foreach( $comment_content as $marker => $content ){
388 $comment_content[$marker] = '<!--'.$content.'-->';
389 }
390 }
391
392 # Extensions
393 foreach ( $this->mTagHooks as $tag => $callback ) {
394 $ext_content[$tag] = array();
395 $text = Parser::extractTags( $tag, $text, $ext_content[$tag], $uniq_prefix );
396 foreach( $ext_content[$tag] as $marker => $content ) {
397 if ( $render ) {
398 $ext_content[$tag][$marker] = $callback( $content );
399 } else {
400 $ext_content[$tag][$marker] = "<$tag>$content</$tag>";
401 }
402 }
403 }
404
405 # Merge state with the pre-existing state, if there is one
406 if ( $state ) {
407 $state['html'] = $state['html'] + $html_content;
408 $state['nowiki'] = $state['nowiki'] + $nowiki_content;
409 $state['math'] = $state['math'] + $math_content;
410 $state['pre'] = $state['pre'] + $pre_content;
411 $state['comment'] = $state['comment'] + $comment_content;
412 $state['gallery'] = $state['gallery'] + $gallery_content;
413
414 foreach( $ext_content as $tag => $array ) {
415 if ( array_key_exists( $tag, $state ) ) {
416 $state[$tag] = $state[$tag] + $array;
417 }
418 }
419 } else {
420 $state = array(
421 'html' => $html_content,
422 'nowiki' => $nowiki_content,
423 'math' => $math_content,
424 'pre' => $pre_content,
425 'comment' => $comment_content,
426 'gallery' => $gallery_content,
427 ) + $ext_content;
428 }
429 return $text;
430 }
431
432 /**
433 * restores pre, math, and hiero removed by strip()
434 *
435 * always call unstripNoWiki() after this one
436 * @access private
437 */
438 function unstrip( $text, &$state ) {
439 # Must expand in reverse order, otherwise nested tags will be corrupted
440 $contentDict = end( $state );
441 for ( $contentDict = end( $state ); $contentDict !== false; $contentDict = prev( $state ) ) {
442 if( key($state) != 'nowiki' && key($state) != 'html') {
443 for ( $content = end( $contentDict ); $content !== false; $content = prev( $contentDict ) ) {
444 $text = str_replace( key( $contentDict ), $content, $text );
445 }
446 }
447 }
448
449 return $text;
450 }
451
452 /**
453 * always call this after unstrip() to preserve the order
454 *
455 * @access private
456 */
457 function unstripNoWiki( $text, &$state ) {
458 # Must expand in reverse order, otherwise nested tags will be corrupted
459 for ( $content = end($state['nowiki']); $content !== false; $content = prev( $state['nowiki'] ) ) {
460 $text = str_replace( key( $state['nowiki'] ), $content, $text );
461 }
462
463 global $wgRawHtml;
464 if ($wgRawHtml) {
465 for ( $content = end($state['html']); $content !== false; $content = prev( $state['html'] ) ) {
466 $text = str_replace( key( $state['html'] ), $content, $text );
467 }
468 }
469
470 return $text;
471 }
472
473 /**
474 * Add an item to the strip state
475 * Returns the unique tag which must be inserted into the stripped text
476 * The tag will be replaced with the original text in unstrip()
477 *
478 * @access private
479 */
480 function insertStripItem( $text, &$state ) {
481 $rnd = UNIQ_PREFIX . '-item' . Parser::getRandomString();
482 if ( !$state ) {
483 $state = array(
484 'html' => array(),
485 'nowiki' => array(),
486 'math' => array(),
487 'pre' => array()
488 );
489 }
490 $state['item'][$rnd] = $text;
491 return $rnd;
492 }
493
494 /**
495 * Interface with html tidy, used if $wgUseTidy = true.
496 * If tidy isn't able to correct the markup, the original will be
497 * returned in all its glory with a warning comment appended.
498 *
499 * Either the external tidy program or the in-process tidy extension
500 * will be used depending on availability. Override the default
501 * $wgTidyInternal setting to disable the internal if it's not working.
502 *
503 * @param string $text Hideous HTML input
504 * @return string Corrected HTML output
505 * @access public
506 * @static
507 */
508 function tidy( $text ) {
509 global $wgTidyInternal;
510 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
511 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
512 '<head><title>test</title></head><body>'.$text.'</body></html>';
513 if( $wgTidyInternal ) {
514 $correctedtext = Parser::internalTidy( $wrappedtext );
515 } else {
516 $correctedtext = Parser::externalTidy( $wrappedtext );
517 }
518 if( is_null( $correctedtext ) ) {
519 wfDebug( "Tidy error detected!\n" );
520 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
521 }
522 return $correctedtext;
523 }
524
525 /**
526 * Spawn an external HTML tidy process and get corrected markup back from it.
527 *
528 * @access private
529 * @static
530 */
531 function externalTidy( $text ) {
532 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
533 $fname = 'Parser::externalTidy';
534 wfProfileIn( $fname );
535
536 $cleansource = '';
537 $opts = ' -utf8';
538
539 $descriptorspec = array(
540 0 => array('pipe', 'r'),
541 1 => array('pipe', 'w'),
542 2 => array('file', '/dev/null', 'a')
543 );
544 $pipes = array();
545 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
546 if (is_resource($process)) {
547 fwrite($pipes[0], $text);
548 fclose($pipes[0]);
549 while (!feof($pipes[1])) {
550 $cleansource .= fgets($pipes[1], 1024);
551 }
552 fclose($pipes[1]);
553 proc_close($process);
554 }
555
556 wfProfileOut( $fname );
557
558 if( $cleansource == '' && $text != '') {
559 // Some kind of error happened, so we couldn't get the corrected text.
560 // Just give up; we'll use the source text and append a warning.
561 return null;
562 } else {
563 return $cleansource;
564 }
565 }
566
567 /**
568 * Use the HTML tidy PECL extension to use the tidy library in-process,
569 * saving the overhead of spawning a new process. Currently written to
570 * the PHP 4.3.x version of the extension, may not work on PHP 5.
571 *
572 * 'pear install tidy' should be able to compile the extension module.
573 *
574 * @access private
575 * @static
576 */
577 function internalTidy( $text ) {
578 global $wgTidyConf;
579 $fname = 'Parser::internalTidy';
580 wfProfileIn( $fname );
581
582 tidy_load_config( $wgTidyConf );
583 tidy_set_encoding( 'utf8' );
584 tidy_parse_string( $text );
585 tidy_clean_repair();
586 if( tidy_get_status() == 2 ) {
587 // 2 is magic number for fatal error
588 // http://www.php.net/manual/en/function.tidy-get-status.php
589 $cleansource = null;
590 } else {
591 $cleansource = tidy_get_output();
592 }
593 wfProfileOut( $fname );
594 return $cleansource;
595 }
596
597 /**
598 * parse the wiki syntax used to render tables
599 *
600 * @access private
601 */
602 function doTableStuff ( $t ) {
603 $fname = 'Parser::doTableStuff';
604 wfProfileIn( $fname );
605
606 $t = explode ( "\n" , $t ) ;
607 $td = array () ; # Is currently a td tag open?
608 $ltd = array () ; # Was it TD or TH?
609 $tr = array () ; # Is currently a tr tag open?
610 $ltr = array () ; # tr attributes
611 $indent_level = 0; # indent level of the table
612 foreach ( $t AS $k => $x )
613 {
614 $x = trim ( $x ) ;
615 $fc = substr ( $x , 0 , 1 ) ;
616 if ( preg_match( '/^(:*)\{\|(.*)$/', $x, $matches ) ) {
617 $indent_level = strlen( $matches[1] );
618 $t[$k] = str_repeat( '<dl><dd>', $indent_level ) .
619 '<table' . Sanitizer::fixTagAttributes ( $matches[2], 'table' ) . '>' ;
620 array_push ( $td , false ) ;
621 array_push ( $ltd , '' ) ;
622 array_push ( $tr , false ) ;
623 array_push ( $ltr , '' ) ;
624 }
625 else if ( count ( $td ) == 0 ) { } # Don't do any of the following
626 else if ( '|}' == substr ( $x , 0 , 2 ) ) {
627 $z = "</table>" . substr ( $x , 2);
628 $l = array_pop ( $ltd ) ;
629 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
630 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
631 array_pop ( $ltr ) ;
632 $t[$k] = $z . str_repeat( '</dd></dl>', $indent_level );
633 }
634 else if ( '|-' == substr ( $x , 0 , 2 ) ) { # Allows for |---------------
635 $x = substr ( $x , 1 ) ;
636 while ( $x != '' && substr ( $x , 0 , 1 ) == '-' ) $x = substr ( $x , 1 ) ;
637 $z = '' ;
638 $l = array_pop ( $ltd ) ;
639 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
640 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
641 array_pop ( $ltr ) ;
642 $t[$k] = $z ;
643 array_push ( $tr , false ) ;
644 array_push ( $td , false ) ;
645 array_push ( $ltd , '' ) ;
646 array_push ( $ltr , Sanitizer::fixTagAttributes ( $x, 'tr' ) ) ;
647 }
648 else if ( '|' == $fc || '!' == $fc || '|+' == substr ( $x , 0 , 2 ) ) { # Caption
649 # $x is a table row
650 if ( '|+' == substr ( $x , 0 , 2 ) ) {
651 $fc = '+' ;
652 $x = substr ( $x , 1 ) ;
653 }
654 $after = substr ( $x , 1 ) ;
655 if ( $fc == '!' ) $after = str_replace ( '!!' , '||' , $after ) ;
656 $after = explode ( '||' , $after ) ;
657 $t[$k] = '' ;
658
659 # Loop through each table cell
660 foreach ( $after AS $theline )
661 {
662 $z = '' ;
663 if ( $fc != '+' )
664 {
665 $tra = array_pop ( $ltr ) ;
666 if ( !array_pop ( $tr ) ) $z = '<tr'.$tra.">\n" ;
667 array_push ( $tr , true ) ;
668 array_push ( $ltr , '' ) ;
669 }
670
671 $l = array_pop ( $ltd ) ;
672 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
673 if ( $fc == '|' ) $l = 'td' ;
674 else if ( $fc == '!' ) $l = 'th' ;
675 else if ( $fc == '+' ) $l = 'caption' ;
676 else $l = '' ;
677 array_push ( $ltd , $l ) ;
678
679 # Cell parameters
680 $y = explode ( '|' , $theline , 2 ) ;
681 # Note that a '|' inside an invalid link should not
682 # be mistaken as delimiting cell parameters
683 if ( strpos( $y[0], '[[' ) !== false ) {
684 $y = array ($theline);
685 }
686 if ( count ( $y ) == 1 )
687 $y = "{$z}<{$l}>{$y[0]}" ;
688 else $y = $y = "{$z}<{$l}".Sanitizer::fixTagAttributes($y[0], $l).">{$y[1]}" ;
689 $t[$k] .= $y ;
690 array_push ( $td , true ) ;
691 }
692 }
693 }
694
695 # Closing open td, tr && table
696 while ( count ( $td ) > 0 )
697 {
698 if ( array_pop ( $td ) ) $t[] = '</td>' ;
699 if ( array_pop ( $tr ) ) $t[] = '</tr>' ;
700 $t[] = '</table>' ;
701 }
702
703 $t = implode ( "\n" , $t ) ;
704 wfProfileOut( $fname );
705 return $t ;
706 }
707
708 /**
709 * Helper function for parse() that transforms wiki markup into
710 * HTML. Only called for $mOutputType == OT_HTML.
711 *
712 * @access private
713 */
714 function internalParse( $text ) {
715 global $wgContLang;
716 $args = array();
717 $isMain = true;
718 $fname = 'Parser::internalParse';
719 wfProfileIn( $fname );
720
721 $text = Sanitizer::removeHTMLtags( $text );
722 $text = $this->replaceVariables( $text, $args );
723
724 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
725
726 $text = $this->doHeadings( $text );
727 if($this->mOptions->getUseDynamicDates()) {
728 $df =& DateFormatter::getInstance();
729 $text = $df->reformat( $this->mOptions->getDateFormat(), $text );
730 }
731 $text = $this->doAllQuotes( $text );
732 $text = $this->replaceInternalLinks( $text );
733 $text = $this->replaceExternalLinks( $text );
734
735 # replaceInternalLinks may sometimes leave behind
736 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
737 $text = str_replace("http-noparse://","http://",$text);
738
739 $text = $this->doMagicLinks( $text );
740 $text = $this->doTableStuff( $text );
741 $text = $this->formatHeadings( $text, $isMain );
742
743 wfProfileOut( $fname );
744 return $text;
745 }
746
747 /**
748 * Replace special strings like "ISBN xxx" and "RFC xxx" with
749 * magic external links.
750 *
751 * @access private
752 */
753 function &doMagicLinks( &$text ) {
754 $text = $this->magicISBN( $text );
755 $text = $this->magicRFC( $text, 'RFC ', 'rfcurl' );
756 $text = $this->magicRFC( $text, 'PMID ', 'pubmedurl' );
757 return $text;
758 }
759
760 /**
761 * Parse ^^ tokens and return html
762 *
763 * @access private
764 */
765 function doExponent( $text ) {
766 $fname = 'Parser::doExponent';
767 wfProfileIn( $fname );
768 $text = preg_replace('/\^\^(.*)\^\^/','<small><sup>\\1</sup></small>', $text);
769 wfProfileOut( $fname );
770 return $text;
771 }
772
773 /**
774 * Parse headers and return html
775 *
776 * @access private
777 */
778 function doHeadings( $text ) {
779 $fname = 'Parser::doHeadings';
780 wfProfileIn( $fname );
781 for ( $i = 6; $i >= 1; --$i ) {
782 $h = substr( '======', 0, $i );
783 $text = preg_replace( "/^{$h}(.+){$h}(\\s|$)/m",
784 "<h{$i}>\\1</h{$i}>\\2", $text );
785 }
786 wfProfileOut( $fname );
787 return $text;
788 }
789
790 /**
791 * Replace single quotes with HTML markup
792 * @access private
793 * @return string the altered text
794 */
795 function doAllQuotes( $text ) {
796 $fname = 'Parser::doAllQuotes';
797 wfProfileIn( $fname );
798 $outtext = '';
799 $lines = explode( "\n", $text );
800 foreach ( $lines as $line ) {
801 $outtext .= $this->doQuotes ( $line ) . "\n";
802 }
803 $outtext = substr($outtext, 0,-1);
804 wfProfileOut( $fname );
805 return $outtext;
806 }
807
808 /**
809 * Helper function for doAllQuotes()
810 * @access private
811 */
812 function doQuotes( $text ) {
813 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE );
814 if ( count( $arr ) == 1 )
815 return $text;
816 else
817 {
818 # First, do some preliminary work. This may shift some apostrophes from
819 # being mark-up to being text. It also counts the number of occurrences
820 # of bold and italics mark-ups.
821 $i = 0;
822 $numbold = 0;
823 $numitalics = 0;
824 foreach ( $arr as $r )
825 {
826 if ( ( $i % 2 ) == 1 )
827 {
828 # If there are ever four apostrophes, assume the first is supposed to
829 # be text, and the remaining three constitute mark-up for bold text.
830 if ( strlen( $arr[$i] ) == 4 )
831 {
832 $arr[$i-1] .= "'";
833 $arr[$i] = "'''";
834 }
835 # If there are more than 5 apostrophes in a row, assume they're all
836 # text except for the last 5.
837 else if ( strlen( $arr[$i] ) > 5 )
838 {
839 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
840 $arr[$i] = "'''''";
841 }
842 # Count the number of occurrences of bold and italics mark-ups.
843 # We are not counting sequences of five apostrophes.
844 if ( strlen( $arr[$i] ) == 2 ) $numitalics++; else
845 if ( strlen( $arr[$i] ) == 3 ) $numbold++; else
846 if ( strlen( $arr[$i] ) == 5 ) { $numitalics++; $numbold++; }
847 }
848 $i++;
849 }
850
851 # If there is an odd number of both bold and italics, it is likely
852 # that one of the bold ones was meant to be an apostrophe followed
853 # by italics. Which one we cannot know for certain, but it is more
854 # likely to be one that has a single-letter word before it.
855 if ( ( $numbold % 2 == 1 ) && ( $numitalics % 2 == 1 ) )
856 {
857 $i = 0;
858 $firstsingleletterword = -1;
859 $firstmultiletterword = -1;
860 $firstspace = -1;
861 foreach ( $arr as $r )
862 {
863 if ( ( $i % 2 == 1 ) and ( strlen( $r ) == 3 ) )
864 {
865 $x1 = substr ($arr[$i-1], -1);
866 $x2 = substr ($arr[$i-1], -2, 1);
867 if ($x1 == ' ') {
868 if ($firstspace == -1) $firstspace = $i;
869 } else if ($x2 == ' ') {
870 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
871 } else {
872 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
873 }
874 }
875 $i++;
876 }
877
878 # If there is a single-letter word, use it!
879 if ($firstsingleletterword > -1)
880 {
881 $arr [ $firstsingleletterword ] = "''";
882 $arr [ $firstsingleletterword-1 ] .= "'";
883 }
884 # If not, but there's a multi-letter word, use that one.
885 else if ($firstmultiletterword > -1)
886 {
887 $arr [ $firstmultiletterword ] = "''";
888 $arr [ $firstmultiletterword-1 ] .= "'";
889 }
890 # ... otherwise use the first one that has neither.
891 # (notice that it is possible for all three to be -1 if, for example,
892 # there is only one pentuple-apostrophe in the line)
893 else if ($firstspace > -1)
894 {
895 $arr [ $firstspace ] = "''";
896 $arr [ $firstspace-1 ] .= "'";
897 }
898 }
899
900 # Now let's actually convert our apostrophic mush to HTML!
901 $output = '';
902 $buffer = '';
903 $state = '';
904 $i = 0;
905 foreach ($arr as $r)
906 {
907 if (($i % 2) == 0)
908 {
909 if ($state == 'both')
910 $buffer .= $r;
911 else
912 $output .= $r;
913 }
914 else
915 {
916 if (strlen ($r) == 2)
917 {
918 if ($state == 'i')
919 { $output .= '</i>'; $state = ''; }
920 else if ($state == 'bi')
921 { $output .= '</i>'; $state = 'b'; }
922 else if ($state == 'ib')
923 { $output .= '</b></i><b>'; $state = 'b'; }
924 else if ($state == 'both')
925 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
926 else # $state can be 'b' or ''
927 { $output .= '<i>'; $state .= 'i'; }
928 }
929 else if (strlen ($r) == 3)
930 {
931 if ($state == 'b')
932 { $output .= '</b>'; $state = ''; }
933 else if ($state == 'bi')
934 { $output .= '</i></b><i>'; $state = 'i'; }
935 else if ($state == 'ib')
936 { $output .= '</b>'; $state = 'i'; }
937 else if ($state == 'both')
938 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
939 else # $state can be 'i' or ''
940 { $output .= '<b>'; $state .= 'b'; }
941 }
942 else if (strlen ($r) == 5)
943 {
944 if ($state == 'b')
945 { $output .= '</b><i>'; $state = 'i'; }
946 else if ($state == 'i')
947 { $output .= '</i><b>'; $state = 'b'; }
948 else if ($state == 'bi')
949 { $output .= '</i></b>'; $state = ''; }
950 else if ($state == 'ib')
951 { $output .= '</b></i>'; $state = ''; }
952 else if ($state == 'both')
953 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
954 else # ($state == '')
955 { $buffer = ''; $state = 'both'; }
956 }
957 }
958 $i++;
959 }
960 # Now close all remaining tags. Notice that the order is important.
961 if ($state == 'b' || $state == 'ib')
962 $output .= '</b>';
963 if ($state == 'i' || $state == 'bi' || $state == 'ib')
964 $output .= '</i>';
965 if ($state == 'bi')
966 $output .= '</b>';
967 if ($state == 'both')
968 $output .= '<b><i>'.$buffer.'</i></b>';
969 return $output;
970 }
971 }
972
973 /**
974 * Replace external links
975 *
976 * Note: this is all very hackish and the order of execution matters a lot.
977 * Make sure to run maintenance/parserTests.php if you change this code.
978 *
979 * @access private
980 */
981 function replaceExternalLinks( $text ) {
982 global $wgContLang;
983 $fname = 'Parser::replaceExternalLinks';
984 wfProfileIn( $fname );
985
986 $sk =& $this->mOptions->getSkin();
987
988 $bits = preg_split( EXT_LINK_BRACKETED, $text, -1, PREG_SPLIT_DELIM_CAPTURE );
989
990 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
991
992 $i = 0;
993 while ( $i<count( $bits ) ) {
994 $url = $bits[$i++];
995 $protocol = $bits[$i++];
996 $text = $bits[$i++];
997 $trail = $bits[$i++];
998
999 # The characters '<' and '>' (which were escaped by
1000 # removeHTMLtags()) should not be included in
1001 # URLs, per RFC 2396.
1002 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE)) {
1003 $text = substr($url, $m2[0][1]) . ' ' . $text;
1004 $url = substr($url, 0, $m2[0][1]);
1005 }
1006
1007 # If the link text is an image URL, replace it with an <img> tag
1008 # This happened by accident in the original parser, but some people used it extensively
1009 $img = $this->maybeMakeExternalImage( $text );
1010 if ( $img !== false ) {
1011 $text = $img;
1012 }
1013
1014 $dtrail = '';
1015
1016 # Set linktype for CSS - if URL==text, link is essentially free
1017 $linktype = ($text == $url) ? 'free' : 'text';
1018
1019 # No link text, e.g. [http://domain.tld/some.link]
1020 if ( $text == '' ) {
1021 # Autonumber if allowed
1022 if ( strpos( HTTP_PROTOCOLS, $protocol ) !== false ) {
1023 $text = '[' . ++$this->mAutonumber . ']';
1024 $linktype = 'autonumber';
1025 } else {
1026 # Otherwise just use the URL
1027 $text = htmlspecialchars( $url );
1028 $linktype = 'free';
1029 }
1030 } else {
1031 # Have link text, e.g. [http://domain.tld/some.link text]s
1032 # Check for trail
1033 list( $dtrail, $trail ) = Linker::splitTrail( $trail );
1034 }
1035
1036 $text = $wgContLang->markNoConversion($text);
1037
1038 # Replace &amp; from obsolete syntax with &.
1039 # All HTML entities will be escaped by makeExternalLink()
1040 # or maybeMakeExternalImage()
1041 $url = str_replace( '&amp;', '&', $url );
1042
1043 # Process the trail (i.e. everything after this link up until start of the next link),
1044 # replacing any non-bracketed links
1045 $trail = $this->replaceFreeExternalLinks( $trail );
1046
1047
1048 # Use the encoded URL
1049 # This means that users can paste URLs directly into the text
1050 # Funny characters like &ouml; aren't valid in URLs anyway
1051 # This was changed in August 2004
1052 $s .= $sk->makeExternalLink( $url, $text, false, $linktype ) . $dtrail . $trail;
1053 }
1054
1055 wfProfileOut( $fname );
1056 return $s;
1057 }
1058
1059 /**
1060 * Replace anything that looks like a URL with a link
1061 * @access private
1062 */
1063 function replaceFreeExternalLinks( $text ) {
1064 global $wgContLang;
1065 $fname = 'Parser::replaceFreeExternalLinks';
1066 wfProfileIn( $fname );
1067
1068 $bits = preg_split( '/(\b(?:'.URL_PROTOCOLS.'):)/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE );
1069 $s = array_shift( $bits );
1070 $i = 0;
1071
1072 $sk =& $this->mOptions->getSkin();
1073
1074 while ( $i < count( $bits ) ){
1075 $protocol = $bits[$i++];
1076 $remainder = $bits[$i++];
1077
1078 if ( preg_match( '/^('.EXT_LINK_URL_CLASS.'+)(.*)$/s', $remainder, $m ) ) {
1079 # Found some characters after the protocol that look promising
1080 $url = $protocol . $m[1];
1081 $trail = $m[2];
1082
1083 # The characters '<' and '>' (which were escaped by
1084 # removeHTMLtags()) should not be included in
1085 # URLs, per RFC 2396.
1086 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE)) {
1087 $trail = substr($url, $m2[0][1]) . $trail;
1088 $url = substr($url, 0, $m2[0][1]);
1089 }
1090
1091 # Move trailing punctuation to $trail
1092 $sep = ',;\.:!?';
1093 # If there is no left bracket, then consider right brackets fair game too
1094 if ( strpos( $url, '(' ) === false ) {
1095 $sep .= ')';
1096 }
1097
1098 $numSepChars = strspn( strrev( $url ), $sep );
1099 if ( $numSepChars ) {
1100 $trail = substr( $url, -$numSepChars ) . $trail;
1101 $url = substr( $url, 0, -$numSepChars );
1102 }
1103
1104 # Replace &amp; from obsolete syntax with &.
1105 # All HTML entities will be escaped by makeExternalLink()
1106 # or maybeMakeExternalImage()
1107 $url = str_replace( '&amp;', '&', $url );
1108
1109 # Is this an external image?
1110 $text = $this->maybeMakeExternalImage( $url );
1111 if ( $text === false ) {
1112 # Not an image, make a link
1113 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free' );
1114 }
1115 $s .= $text . $trail;
1116 } else {
1117 $s .= $protocol . $remainder;
1118 }
1119 }
1120 wfProfileOut();
1121 return $s;
1122 }
1123
1124 /**
1125 * make an image if it's allowed
1126 * @access private
1127 */
1128 function maybeMakeExternalImage( $url ) {
1129 $sk =& $this->mOptions->getSkin();
1130 $text = false;
1131 if ( $this->mOptions->getAllowExternalImages() ) {
1132 if ( preg_match( EXT_IMAGE_REGEX, $url ) ) {
1133 # Image found
1134 $text = $sk->makeExternalImage( htmlspecialchars( $url ) );
1135 }
1136 }
1137 return $text;
1138 }
1139
1140 /**
1141 * Process [[ ]] wikilinks
1142 *
1143 * @access private
1144 */
1145 function replaceInternalLinks( $s ) {
1146 global $wgContLang, $wgLinkCache;
1147 static $fname = 'Parser::replaceInternalLinks' ;
1148
1149 wfProfileIn( $fname );
1150
1151 wfProfileIn( $fname.'-setup' );
1152 static $tc = FALSE;
1153 # the % is needed to support urlencoded titles as well
1154 if ( !$tc ) { $tc = Title::legalChars() . '#%'; }
1155
1156 $sk =& $this->mOptions->getSkin();
1157
1158 #split the entire text string on occurences of [[
1159 $a = explode( '[[', ' ' . $s );
1160 #get the first element (all text up to first [[), and remove the space we added
1161 $s = array_shift( $a );
1162 $s = substr( $s, 1 );
1163
1164 # Match a link having the form [[namespace:link|alternate]]trail
1165 static $e1 = FALSE;
1166 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1167 # Match cases where there is no "]]", which might still be images
1168 static $e1_img = FALSE;
1169 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1170 # Match the end of a line for a word that's not followed by whitespace,
1171 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1172 static $e2 = '/^(.*?)([a-zA-Z\x80-\xff]+)$/sD';
1173
1174 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1175
1176 if( is_null( $this->mTitle ) ) {
1177 wfDebugDieBacktrace( 'nooo' );
1178 }
1179 $nottalk = !$this->mTitle->isTalkPage();
1180
1181 if ( $useLinkPrefixExtension ) {
1182 if ( preg_match( $e2, $s, $m ) ) {
1183 $first_prefix = $m[2];
1184 $s = $m[1];
1185 } else {
1186 $first_prefix = false;
1187 }
1188 } else {
1189 $prefix = '';
1190 }
1191
1192 $selflink = $this->mTitle->getPrefixedText();
1193 wfProfileOut( $fname.'-setup' );
1194
1195 $checkVariantLink = sizeof($wgContLang->getVariants())>1;
1196 $useSubpages = $this->areSubpagesAllowed();
1197
1198 # Loop for each link
1199 for ($k = 0; isset( $a[$k] ); $k++) {
1200 $line = $a[$k];
1201 if ( $useLinkPrefixExtension ) {
1202 wfProfileIn( $fname.'-prefixhandling' );
1203 if ( preg_match( $e2, $s, $m ) ) {
1204 $prefix = $m[2];
1205 $s = $m[1];
1206 } else {
1207 $prefix='';
1208 }
1209 # first link
1210 if($first_prefix) {
1211 $prefix = $first_prefix;
1212 $first_prefix = false;
1213 }
1214 wfProfileOut( $fname.'-prefixhandling' );
1215 }
1216
1217 $might_be_img = false;
1218
1219 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1220 $text = $m[2];
1221 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1222 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1223 # the real problem is with the $e1 regex
1224 # See bug 1300.
1225 if (preg_match( "/^\](.*)/s", $m[3], $n ) ) {
1226 $text .= ']'; # so that replaceExternalLinks($text) works later
1227 $m[3] = $n[1];
1228 }
1229 # fix up urlencoded title texts
1230 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1231 $trail = $m[3];
1232 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1233 $might_be_img = true;
1234 $text = $m[2];
1235 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1236 $trail = "";
1237 } else { # Invalid form; output directly
1238 $s .= $prefix . '[[' . $line ;
1239 continue;
1240 }
1241
1242 # Don't allow internal links to pages containing
1243 # PROTO: where PROTO is a valid URL protocol; these
1244 # should be external links.
1245 if (preg_match('/^(\b(?:'.URL_PROTOCOLS.'):)/', $m[1])) {
1246 $s .= $prefix . '[[' . $line ;
1247 continue;
1248 }
1249
1250 # Make subpage if necessary
1251 if( $useSubpages ) {
1252 $link = $this->maybeDoSubpageLink( $m[1], $text );
1253 } else {
1254 $link = $m[1];
1255 }
1256
1257 $noforce = (substr($m[1], 0, 1) != ':');
1258 if (!$noforce) {
1259 # Strip off leading ':'
1260 $link = substr($link, 1);
1261 }
1262
1263 $nt =& Title::newFromText( $this->unstripNoWiki($link, $this->mStripState) );
1264 if( !$nt ) {
1265 $s .= $prefix . '[[' . $line;
1266 continue;
1267 }
1268
1269 #check other language variants of the link
1270 #if the article does not exist
1271 if( $checkVariantLink
1272 && $nt->getArticleID() == 0 ) {
1273 $wgContLang->findVariantLink($link, $nt);
1274 }
1275
1276 $ns = $nt->getNamespace();
1277 $iw = $nt->getInterWiki();
1278
1279 if ($might_be_img) { # if this is actually an invalid link
1280 if ($ns == NS_IMAGE && $noforce) { #but might be an image
1281 $found = false;
1282 while (isset ($a[$k+1]) ) {
1283 #look at the next 'line' to see if we can close it there
1284 $next_line = array_shift(array_splice( $a, $k + 1, 1) );
1285 if( preg_match("/^(.*?]].*?)]](.*)$/sD", $next_line, $m) ) {
1286 # the first ]] closes the inner link, the second the image
1287 $found = true;
1288 $text .= '[[' . $m[1];
1289 $trail = $m[2];
1290 break;
1291 } elseif( preg_match("/^.*?]].*$/sD", $next_line, $m) ) {
1292 #if there's exactly one ]] that's fine, we'll keep looking
1293 $text .= '[[' . $m[0];
1294 } else {
1295 #if $next_line is invalid too, we need look no further
1296 $text .= '[[' . $next_line;
1297 break;
1298 }
1299 }
1300 if ( !$found ) {
1301 # we couldn't find the end of this imageLink, so output it raw
1302 #but don't ignore what might be perfectly normal links in the text we've examined
1303 $text = $this->replaceInternalLinks($text);
1304 $s .= $prefix . '[[' . $link . '|' . $text;
1305 # note: no $trail, because without an end, there *is* no trail
1306 continue;
1307 }
1308 } else { #it's not an image, so output it raw
1309 $s .= $prefix . '[[' . $link . '|' . $text;
1310 # note: no $trail, because without an end, there *is* no trail
1311 continue;
1312 }
1313 }
1314
1315 $wasblank = ( '' == $text );
1316 if( $wasblank ) $text = $link;
1317
1318
1319 # Link not escaped by : , create the various objects
1320 if( $noforce ) {
1321
1322 # Interwikis
1323 if( $iw && $this->mOptions->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1324 array_push( $this->mOutput->mLanguageLinks, $nt->getFullText() );
1325 $s = rtrim($s . "\n");
1326 $s .= trim($prefix . $trail, "\n") == '' ? '': $prefix . $trail;
1327 continue;
1328 }
1329
1330 if ( $ns == NS_IMAGE ) {
1331 wfProfileIn( "$fname-image" );
1332 if ( !wfIsBadImage( $nt->getDBkey() ) ) {
1333 # recursively parse links inside the image caption
1334 # actually, this will parse them in any other parameters, too,
1335 # but it might be hard to fix that, and it doesn't matter ATM
1336 $text = $this->replaceExternalLinks($text);
1337 $text = $this->replaceInternalLinks($text);
1338
1339 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1340 $s .= $prefix . str_replace('http://', 'http-noparse://', $this->makeImage( $nt, $text ) ) . $trail;
1341 $wgLinkCache->addImageLinkObj( $nt );
1342
1343 wfProfileOut( "$fname-image" );
1344 continue;
1345 }
1346 wfProfileOut( "$fname-image" );
1347
1348 }
1349
1350 if ( $ns == NS_CATEGORY ) {
1351 wfProfileIn( "$fname-category" );
1352 $t = $wgContLang->convert($nt->getText());
1353 $s = rtrim($s . "\n"); # bug 87
1354
1355 $wgLinkCache->suspend(); # Don't save in links/brokenlinks
1356 $t = $sk->makeLinkObj( $nt, $t, '', '' , $prefix );
1357 $wgLinkCache->resume();
1358
1359 if ( $wasblank ) {
1360 if ( $this->mTitle->getNamespace() == NS_CATEGORY ) {
1361 $sortkey = $this->mTitle->getText();
1362 } else {
1363 $sortkey = $this->mTitle->getPrefixedText();
1364 }
1365 } else {
1366 $sortkey = $text;
1367 }
1368 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1369 $wgLinkCache->addCategoryLinkObj( $nt, $sortkey );
1370 $this->mOutput->addCategoryLink( $t );
1371
1372 /**
1373 * Strip the whitespace Category links produce, see bug 87
1374 * @todo We might want to use trim($tmp, "\n") here.
1375 */
1376 $s .= trim($prefix . $trail, "\n") == '' ? '': $prefix . $trail;
1377
1378 wfProfileOut( "$fname-category" );
1379 continue;
1380 }
1381 }
1382
1383 if( ( $nt->getPrefixedText() === $selflink ) &&
1384 ( $nt->getFragment() === '' ) ) {
1385 # Self-links are handled specially; generally de-link and change to bold.
1386 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1387 continue;
1388 }
1389
1390 # Special and Media are pseudo-namespaces; no pages actually exist in them
1391 if( $ns == NS_MEDIA ) {
1392 $s .= $prefix . $sk->makeMediaLinkObj( $nt, $text, true ) . $trail;
1393 $wgLinkCache->addImageLinkObj( $nt );
1394 continue;
1395 } elseif( $ns == NS_SPECIAL ) {
1396 $s .= $prefix . $sk->makeKnownLinkObj( $nt, $text, '', $trail );
1397 continue;
1398 }
1399 if ( $nt->isAlwaysKnown() ) {
1400 $s .= $sk->makeKnownLinkObj( $nt, $text, '', $trail, $prefix );
1401 } else {
1402 /**
1403 * Add a link placeholder
1404 * Later, this will be replaced by a real link, after the existence or
1405 * non-existence of all the links is known
1406 */
1407 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1408 }
1409 }
1410 wfProfileOut( $fname );
1411 return $s;
1412 }
1413
1414 /**
1415 * Make a link placeholder. The text returned can be later resolved to a real link with
1416 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1417 * parsing of interwiki links, and secondly to allow all extistence checks and
1418 * article length checks (for stub links) to be bundled into a single query.
1419 *
1420 */
1421 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1422 if ( ! is_object($nt) ) {
1423 # Fail gracefully
1424 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1425 } else {
1426 # Separate the link trail from the rest of the link
1427 list( $inside, $trail ) = Linker::splitTrail( $trail );
1428
1429 if ( $nt->isExternal() ) {
1430 $iwRecord = array( $nt->getPrefixedDBkey(), $prefix.$text.$inside );
1431 $nr = array_push($this->mInterwikiLinkHolders, $iwRecord);
1432 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1433 } else {
1434 $nr = array_push( $this->mLinkHolders['namespaces'], $nt->getNamespace() );
1435 $this->mLinkHolders['dbkeys'][] = $nt->getDBkey();
1436 $this->mLinkHolders['queries'][] = $query;
1437 $this->mLinkHolders['texts'][] = $prefix.$text.$inside;
1438 $this->mLinkHolders['titles'][] =& $nt;
1439
1440 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1441 }
1442 }
1443 return $retVal;
1444 }
1445
1446 /**
1447 * Return true if subpage links should be expanded on this page.
1448 * @return bool
1449 */
1450 function areSubpagesAllowed() {
1451 # Some namespaces don't allow subpages
1452 global $wgNamespacesWithSubpages;
1453 return !empty($wgNamespacesWithSubpages[$this->mTitle->getNamespace()]);
1454 }
1455
1456 /**
1457 * Handle link to subpage if necessary
1458 * @param string $target the source of the link
1459 * @param string &$text the link text, modified as necessary
1460 * @return string the full name of the link
1461 * @access private
1462 */
1463 function maybeDoSubpageLink($target, &$text) {
1464 # Valid link forms:
1465 # Foobar -- normal
1466 # :Foobar -- override special treatment of prefix (images, language links)
1467 # /Foobar -- convert to CurrentPage/Foobar
1468 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1469 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1470 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1471
1472 $fname = 'Parser::maybeDoSubpageLink';
1473 wfProfileIn( $fname );
1474 $ret = $target; # default return value is no change
1475
1476 # Some namespaces don't allow subpages,
1477 # so only perform processing if subpages are allowed
1478 if( $this->areSubpagesAllowed() ) {
1479 # Look at the first character
1480 if( $target != '' && $target{0} == '/' ) {
1481 # / at end means we don't want the slash to be shown
1482 if( substr( $target, -1, 1 ) == '/' ) {
1483 $target = substr( $target, 1, -1 );
1484 $noslash = $target;
1485 } else {
1486 $noslash = substr( $target, 1 );
1487 }
1488
1489 $ret = $this->mTitle->getPrefixedText(). '/' . trim($noslash);
1490 if( '' === $text ) {
1491 $text = $target;
1492 } # this might be changed for ugliness reasons
1493 } else {
1494 # check for .. subpage backlinks
1495 $dotdotcount = 0;
1496 $nodotdot = $target;
1497 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1498 ++$dotdotcount;
1499 $nodotdot = substr( $nodotdot, 3 );
1500 }
1501 if($dotdotcount > 0) {
1502 $exploded = explode( '/', $this->mTitle->GetPrefixedText() );
1503 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1504 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1505 # / at the end means don't show full path
1506 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1507 $nodotdot = substr( $nodotdot, 0, -1 );
1508 if( '' === $text ) {
1509 $text = $nodotdot;
1510 }
1511 }
1512 $nodotdot = trim( $nodotdot );
1513 if( $nodotdot != '' ) {
1514 $ret .= '/' . $nodotdot;
1515 }
1516 }
1517 }
1518 }
1519 }
1520
1521 wfProfileOut( $fname );
1522 return $ret;
1523 }
1524
1525 /**#@+
1526 * Used by doBlockLevels()
1527 * @access private
1528 */
1529 /* private */ function closeParagraph() {
1530 $result = '';
1531 if ( '' != $this->mLastSection ) {
1532 $result = '</' . $this->mLastSection . ">\n";
1533 }
1534 $this->mInPre = false;
1535 $this->mLastSection = '';
1536 return $result;
1537 }
1538 # getCommon() returns the length of the longest common substring
1539 # of both arguments, starting at the beginning of both.
1540 #
1541 /* private */ function getCommon( $st1, $st2 ) {
1542 $fl = strlen( $st1 );
1543 $shorter = strlen( $st2 );
1544 if ( $fl < $shorter ) { $shorter = $fl; }
1545
1546 for ( $i = 0; $i < $shorter; ++$i ) {
1547 if ( $st1{$i} != $st2{$i} ) { break; }
1548 }
1549 return $i;
1550 }
1551 # These next three functions open, continue, and close the list
1552 # element appropriate to the prefix character passed into them.
1553 #
1554 /* private */ function openList( $char ) {
1555 $result = $this->closeParagraph();
1556
1557 if ( '*' == $char ) { $result .= '<ul><li>'; }
1558 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1559 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1560 else if ( ';' == $char ) {
1561 $result .= '<dl><dt>';
1562 $this->mDTopen = true;
1563 }
1564 else { $result = '<!-- ERR 1 -->'; }
1565
1566 return $result;
1567 }
1568
1569 /* private */ function nextItem( $char ) {
1570 if ( '*' == $char || '#' == $char ) { return '</li><li>'; }
1571 else if ( ':' == $char || ';' == $char ) {
1572 $close = '</dd>';
1573 if ( $this->mDTopen ) { $close = '</dt>'; }
1574 if ( ';' == $char ) {
1575 $this->mDTopen = true;
1576 return $close . '<dt>';
1577 } else {
1578 $this->mDTopen = false;
1579 return $close . '<dd>';
1580 }
1581 }
1582 return '<!-- ERR 2 -->';
1583 }
1584
1585 /* private */ function closeList( $char ) {
1586 if ( '*' == $char ) { $text = '</li></ul>'; }
1587 else if ( '#' == $char ) { $text = '</li></ol>'; }
1588 else if ( ':' == $char ) {
1589 if ( $this->mDTopen ) {
1590 $this->mDTopen = false;
1591 $text = '</dt></dl>';
1592 } else {
1593 $text = '</dd></dl>';
1594 }
1595 }
1596 else { return '<!-- ERR 3 -->'; }
1597 return $text."\n";
1598 }
1599 /**#@-*/
1600
1601 /**
1602 * Make lists from lines starting with ':', '*', '#', etc.
1603 *
1604 * @access private
1605 * @return string the lists rendered as HTML
1606 */
1607 function doBlockLevels( $text, $linestart ) {
1608 $fname = 'Parser::doBlockLevels';
1609 wfProfileIn( $fname );
1610
1611 # Parsing through the text line by line. The main thing
1612 # happening here is handling of block-level elements p, pre,
1613 # and making lists from lines starting with * # : etc.
1614 #
1615 $textLines = explode( "\n", $text );
1616
1617 $lastPrefix = $output = '';
1618 $this->mDTopen = $inBlockElem = false;
1619 $prefixLength = 0;
1620 $paragraphStack = false;
1621
1622 if ( !$linestart ) {
1623 $output .= array_shift( $textLines );
1624 }
1625 foreach ( $textLines as $oLine ) {
1626 $lastPrefixLength = strlen( $lastPrefix );
1627 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
1628 $preOpenMatch = preg_match('/<pre/i', $oLine );
1629 if ( !$this->mInPre ) {
1630 # Multiple prefixes may abut each other for nested lists.
1631 $prefixLength = strspn( $oLine, '*#:;' );
1632 $pref = substr( $oLine, 0, $prefixLength );
1633
1634 # eh?
1635 $pref2 = str_replace( ';', ':', $pref );
1636 $t = substr( $oLine, $prefixLength );
1637 $this->mInPre = !empty($preOpenMatch);
1638 } else {
1639 # Don't interpret any other prefixes in preformatted text
1640 $prefixLength = 0;
1641 $pref = $pref2 = '';
1642 $t = $oLine;
1643 }
1644
1645 # List generation
1646 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
1647 # Same as the last item, so no need to deal with nesting or opening stuff
1648 $output .= $this->nextItem( substr( $pref, -1 ) );
1649 $paragraphStack = false;
1650
1651 if ( substr( $pref, -1 ) == ';') {
1652 # The one nasty exception: definition lists work like this:
1653 # ; title : definition text
1654 # So we check for : in the remainder text to split up the
1655 # title and definition, without b0rking links.
1656 $term = $t2 = '';
1657 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1658 $t = $t2;
1659 $output .= $term . $this->nextItem( ':' );
1660 }
1661 }
1662 } elseif( $prefixLength || $lastPrefixLength ) {
1663 # Either open or close a level...
1664 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
1665 $paragraphStack = false;
1666
1667 while( $commonPrefixLength < $lastPrefixLength ) {
1668 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
1669 --$lastPrefixLength;
1670 }
1671 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
1672 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
1673 }
1674 while ( $prefixLength > $commonPrefixLength ) {
1675 $char = substr( $pref, $commonPrefixLength, 1 );
1676 $output .= $this->openList( $char );
1677
1678 if ( ';' == $char ) {
1679 # FIXME: This is dupe of code above
1680 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1681 $t = $t2;
1682 $output .= $term . $this->nextItem( ':' );
1683 }
1684 }
1685 ++$commonPrefixLength;
1686 }
1687 $lastPrefix = $pref2;
1688 }
1689 if( 0 == $prefixLength ) {
1690 wfProfileIn( "$fname-paragraph" );
1691 # No prefix (not in list)--go to paragraph mode
1692 $uniq_prefix = UNIQ_PREFIX;
1693 // XXX: use a stack for nestable elements like span, table and div
1694 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
1695 $closematch = preg_match(
1696 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
1697 '<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|'.$uniq_prefix.'-pre|<\\/li|<\\/ul)/iS', $t );
1698 if ( $openmatch or $closematch ) {
1699 $paragraphStack = false;
1700 $output .= $this->closeParagraph();
1701 if($preOpenMatch and !$preCloseMatch) {
1702 $this->mInPre = true;
1703 }
1704 if ( $closematch ) {
1705 $inBlockElem = false;
1706 } else {
1707 $inBlockElem = true;
1708 }
1709 } else if ( !$inBlockElem && !$this->mInPre ) {
1710 if ( ' ' == $t{0} and ( $this->mLastSection == 'pre' or trim($t) != '' ) ) {
1711 // pre
1712 if ($this->mLastSection != 'pre') {
1713 $paragraphStack = false;
1714 $output .= $this->closeParagraph().'<pre>';
1715 $this->mLastSection = 'pre';
1716 }
1717 $t = substr( $t, 1 );
1718 } else {
1719 // paragraph
1720 if ( '' == trim($t) ) {
1721 if ( $paragraphStack ) {
1722 $output .= $paragraphStack.'<br />';
1723 $paragraphStack = false;
1724 $this->mLastSection = 'p';
1725 } else {
1726 if ($this->mLastSection != 'p' ) {
1727 $output .= $this->closeParagraph();
1728 $this->mLastSection = '';
1729 $paragraphStack = '<p>';
1730 } else {
1731 $paragraphStack = '</p><p>';
1732 }
1733 }
1734 } else {
1735 if ( $paragraphStack ) {
1736 $output .= $paragraphStack;
1737 $paragraphStack = false;
1738 $this->mLastSection = 'p';
1739 } else if ($this->mLastSection != 'p') {
1740 $output .= $this->closeParagraph().'<p>';
1741 $this->mLastSection = 'p';
1742 }
1743 }
1744 }
1745 }
1746 wfProfileOut( "$fname-paragraph" );
1747 }
1748 if ($paragraphStack === false) {
1749 $output .= $t."\n";
1750 }
1751 }
1752 while ( $prefixLength ) {
1753 $output .= $this->closeList( $pref2{$prefixLength-1} );
1754 --$prefixLength;
1755 }
1756 if ( '' != $this->mLastSection ) {
1757 $output .= '</' . $this->mLastSection . '>';
1758 $this->mLastSection = '';
1759 }
1760
1761 wfProfileOut( $fname );
1762 return $output;
1763 }
1764
1765 /**
1766 * Split up a string on ':', ignoring any occurences inside
1767 * <a>..</a> or <span>...</span>
1768 * @param string $str the string to split
1769 * @param string &$before set to everything before the ':'
1770 * @param string &$after set to everything after the ':'
1771 * return string the position of the ':', or false if none found
1772 */
1773 function findColonNoLinks($str, &$before, &$after) {
1774 # I wonder if we should make this count all tags, not just <a>
1775 # and <span>. That would prevent us from matching a ':' that
1776 # comes in the middle of italics other such formatting....
1777 # -- Wil
1778 $fname = 'Parser::findColonNoLinks';
1779 wfProfileIn( $fname );
1780 $pos = 0;
1781 do {
1782 $colon = strpos($str, ':', $pos);
1783
1784 if ($colon !== false) {
1785 $before = substr($str, 0, $colon);
1786 $after = substr($str, $colon + 1);
1787
1788 # Skip any ':' within <a> or <span> pairs
1789 $a = substr_count($before, '<a');
1790 $s = substr_count($before, '<span');
1791 $ca = substr_count($before, '</a>');
1792 $cs = substr_count($before, '</span>');
1793
1794 if ($a <= $ca and $s <= $cs) {
1795 # Tags are balanced before ':'; ok
1796 break;
1797 }
1798 $pos = $colon + 1;
1799 }
1800 } while ($colon !== false);
1801 wfProfileOut( $fname );
1802 return $colon;
1803 }
1804
1805 /**
1806 * Return value of a magic variable (like PAGENAME)
1807 *
1808 * @access private
1809 */
1810 function getVariableValue( $index ) {
1811 global $wgContLang, $wgSitename, $wgServer, $wgArticle;
1812
1813 /**
1814 * Some of these require message or data lookups and can be
1815 * expensive to check many times.
1816 */
1817 static $varCache = array();
1818 if( isset( $varCache[$index] ) ) return $varCache[$index];
1819
1820 switch ( $index ) {
1821 case MAG_CURRENTMONTH:
1822 return $varCache[$index] = $wgContLang->formatNum( date( 'm' ) );
1823 case MAG_CURRENTMONTHNAME:
1824 return $varCache[$index] = $wgContLang->getMonthName( date('n') );
1825 case MAG_CURRENTMONTHNAMEGEN:
1826 return $varCache[$index] = $wgContLang->getMonthNameGen( date('n') );
1827 case MAG_CURRENTMONTHABBREV:
1828 return $varCache[$index] = $wgContLang->getMonthAbbreviation( date('n') );
1829 case MAG_CURRENTDAY:
1830 return $varCache[$index] = $wgContLang->formatNum( date('j') );
1831 case MAG_PAGENAME:
1832 return $this->mTitle->getText();
1833 case MAG_PAGENAMEE:
1834 return $this->mTitle->getPartialURL();
1835 case MAG_REVISIONID:
1836 return $wgArticle->getRevIdFetched();
1837 case MAG_NAMESPACE:
1838 # return Namespace::getCanonicalName($this->mTitle->getNamespace());
1839 return $wgContLang->getNsText($this->mTitle->getNamespace()); # Patch by Dori
1840 case MAG_CURRENTDAYNAME:
1841 return $varCache[$index] = $wgContLang->getWeekdayName( date('w')+1 );
1842 case MAG_CURRENTYEAR:
1843 return $varCache[$index] = $wgContLang->formatNum( date( 'Y' ), true );
1844 case MAG_CURRENTTIME:
1845 return $varCache[$index] = $wgContLang->time( wfTimestampNow(), false );
1846 case MAG_CURRENTWEEK:
1847 return $varCache[$index] = $wgContLang->formatNum( date('W') );
1848 case MAG_CURRENTDOW:
1849 return $varCache[$index] = $wgContLang->formatNum( date('w') );
1850 case MAG_NUMBEROFARTICLES:
1851 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfArticles() );
1852 case MAG_SITENAME:
1853 return $wgSitename;
1854 case MAG_SERVER:
1855 return $wgServer;
1856 default:
1857 return NULL;
1858 }
1859 }
1860
1861 /**
1862 * initialise the magic variables (like CURRENTMONTHNAME)
1863 *
1864 * @access private
1865 */
1866 function initialiseVariables() {
1867 $fname = 'Parser::initialiseVariables';
1868 wfProfileIn( $fname );
1869 global $wgVariableIDs;
1870 $this->mVariables = array();
1871 foreach ( $wgVariableIDs as $id ) {
1872 $mw =& MagicWord::get( $id );
1873 $mw->addToArray( $this->mVariables, $id );
1874 }
1875 wfProfileOut( $fname );
1876 }
1877
1878 /**
1879 * Replace magic variables, templates, and template arguments
1880 * with the appropriate text. Templates are substituted recursively,
1881 * taking care to avoid infinite loops.
1882 *
1883 * Note that the substitution depends on value of $mOutputType:
1884 * OT_WIKI: only {{subst:}} templates
1885 * OT_MSG: only magic variables
1886 * OT_HTML: all templates and magic variables
1887 *
1888 * @param string $tex The text to transform
1889 * @param array $args Key-value pairs representing template parameters to substitute
1890 * @access private
1891 */
1892 function replaceVariables( $text, $args = array() ) {
1893
1894 # Prevent too big inclusions
1895 if( strlen( $text ) > MAX_INCLUDE_SIZE ) {
1896 return $text;
1897 }
1898
1899 $fname = 'Parser::replaceVariables';
1900 wfProfileIn( $fname );
1901
1902 $titleChars = Title::legalChars();
1903
1904 # This function is called recursively. To keep track of arguments we need a stack:
1905 array_push( $this->mArgStack, $args );
1906
1907 # Variable substitution
1908 $text = preg_replace_callback( "/{{([$titleChars]*?)}}/", array( &$this, 'variableSubstitution' ), $text );
1909
1910 if ( $this->mOutputType == OT_HTML || $this->mOutputType == OT_WIKI ) {
1911 # Argument substitution
1912 $text = preg_replace_callback( "/{{{([$titleChars]*?)}}}/", array( &$this, 'argSubstitution' ), $text );
1913 }
1914 # Template substitution
1915 $regex = '/(\\n|{)?{{(['.$titleChars.']*)(\\|.*?|)}}/s';
1916 $text = preg_replace_callback( $regex, array( &$this, 'braceSubstitution' ), $text );
1917
1918 array_pop( $this->mArgStack );
1919
1920 wfProfileOut( $fname );
1921 return $text;
1922 }
1923
1924 /**
1925 * Replace magic variables
1926 * @access private
1927 */
1928 function variableSubstitution( $matches ) {
1929 $fname = 'parser::variableSubstitution';
1930 $varname = $matches[1];
1931 wfProfileIn( $fname );
1932 if ( !$this->mVariables ) {
1933 $this->initialiseVariables();
1934 }
1935 $skip = false;
1936 if ( $this->mOutputType == OT_WIKI ) {
1937 # Do only magic variables prefixed by SUBST
1938 $mwSubst =& MagicWord::get( MAG_SUBST );
1939 if (!$mwSubst->matchStartAndRemove( $varname ))
1940 $skip = true;
1941 # Note that if we don't substitute the variable below,
1942 # we don't remove the {{subst:}} magic word, in case
1943 # it is a template rather than a magic variable.
1944 }
1945 if ( !$skip && array_key_exists( $varname, $this->mVariables ) ) {
1946 $id = $this->mVariables[$varname];
1947 $text = $this->getVariableValue( $id );
1948 $this->mOutput->mContainsOldMagic = true;
1949 } else {
1950 $text = $matches[0];
1951 }
1952 wfProfileOut( $fname );
1953 return $text;
1954 }
1955
1956 # Split template arguments
1957 function getTemplateArgs( $argsString ) {
1958 if ( $argsString === '' ) {
1959 return array();
1960 }
1961
1962 $args = explode( '|', substr( $argsString, 1 ) );
1963
1964 # If any of the arguments contains a '[[' but no ']]', it needs to be
1965 # merged with the next arg because the '|' character between belongs
1966 # to the link syntax and not the template parameter syntax.
1967 $argc = count($args);
1968
1969 for ( $i = 0; $i < $argc-1; $i++ ) {
1970 if ( substr_count ( $args[$i], '[[' ) != substr_count ( $args[$i], ']]' ) ) {
1971 $args[$i] .= '|'.$args[$i+1];
1972 array_splice($args, $i+1, 1);
1973 $i--;
1974 $argc--;
1975 }
1976 }
1977
1978 return $args;
1979 }
1980
1981 /**
1982 * Return the text of a template, after recursively
1983 * replacing any variables or templates within the template.
1984 *
1985 * @param array $matches The parts of the template
1986 * $matches[1]: the title, i.e. the part before the |
1987 * $matches[2]: the parameters (including a leading |), if any
1988 * @return string the text of the template
1989 * @access private
1990 */
1991 function braceSubstitution( $matches ) {
1992 global $wgLinkCache, $wgContLang;
1993 $fname = 'Parser::braceSubstitution';
1994 wfProfileIn( $fname );
1995
1996 $found = false;
1997 $nowiki = false;
1998 $noparse = false;
1999
2000 $title = NULL;
2001
2002 # Need to know if the template comes at the start of a line,
2003 # to treat the beginning of the template like the beginning
2004 # of a line for tables and block-level elements.
2005 $linestart = $matches[1];
2006
2007 # $part1 is the bit before the first |, and must contain only title characters
2008 # $args is a list of arguments, starting from index 0, not including $part1
2009
2010 $part1 = $matches[2];
2011 # If the third subpattern matched anything, it will start with |
2012
2013 $args = $this->getTemplateArgs($matches[3]);
2014 $argc = count( $args );
2015
2016 # Don't parse {{{}}} because that's only for template arguments
2017 if ( $linestart === '{' ) {
2018 $text = $matches[0];
2019 $found = true;
2020 $noparse = true;
2021 }
2022
2023 # SUBST
2024 if ( !$found ) {
2025 $mwSubst =& MagicWord::get( MAG_SUBST );
2026 if ( $mwSubst->matchStartAndRemove( $part1 ) xor ($this->mOutputType == OT_WIKI) ) {
2027 # One of two possibilities is true:
2028 # 1) Found SUBST but not in the PST phase
2029 # 2) Didn't find SUBST and in the PST phase
2030 # In either case, return without further processing
2031 $text = $matches[0];
2032 $found = true;
2033 $noparse = true;
2034 }
2035 }
2036
2037 # MSG, MSGNW and INT
2038 if ( !$found ) {
2039 # Check for MSGNW:
2040 $mwMsgnw =& MagicWord::get( MAG_MSGNW );
2041 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2042 $nowiki = true;
2043 }
2044
2045 # Check if it is an internal message
2046 $mwInt =& MagicWord::get( MAG_INT );
2047 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
2048 if ( $this->incrementIncludeCount( 'int:'.$part1 ) ) {
2049 $text = $linestart . wfMsgReal( $part1, $args, true );
2050 $found = true;
2051 }
2052 }
2053 }
2054
2055 # NS
2056 if ( !$found ) {
2057 # Check for NS: (namespace expansion)
2058 $mwNs = MagicWord::get( MAG_NS );
2059 if ( $mwNs->matchStartAndRemove( $part1 ) ) {
2060 if ( intval( $part1 ) ) {
2061 $text = $linestart . $wgContLang->getNsText( intval( $part1 ) );
2062 $found = true;
2063 } else {
2064 $index = Namespace::getCanonicalIndex( strtolower( $part1 ) );
2065 if ( !is_null( $index ) ) {
2066 $text = $linestart . $wgContLang->getNsText( $index );
2067 $found = true;
2068 }
2069 }
2070 }
2071 }
2072
2073 # LOCALURL and LOCALURLE
2074 if ( !$found ) {
2075 $mwLocal = MagicWord::get( MAG_LOCALURL );
2076 $mwLocalE = MagicWord::get( MAG_LOCALURLE );
2077
2078 if ( $mwLocal->matchStartAndRemove( $part1 ) ) {
2079 $func = 'getLocalURL';
2080 } elseif ( $mwLocalE->matchStartAndRemove( $part1 ) ) {
2081 $func = 'escapeLocalURL';
2082 } else {
2083 $func = '';
2084 }
2085
2086 if ( $func !== '' ) {
2087 $title = Title::newFromText( $part1 );
2088 if ( !is_null( $title ) ) {
2089 if ( $argc > 0 ) {
2090 $text = $linestart . $title->$func( $args[0] );
2091 } else {
2092 $text = $linestart . $title->$func();
2093 }
2094 $found = true;
2095 }
2096 }
2097 }
2098
2099 # GRAMMAR
2100 if ( !$found && $argc == 1 ) {
2101 $mwGrammar =& MagicWord::get( MAG_GRAMMAR );
2102 if ( $mwGrammar->matchStartAndRemove( $part1 ) ) {
2103 $text = $linestart . $wgContLang->convertGrammar( $args[0], $part1 );
2104 $found = true;
2105 }
2106 }
2107
2108 # Template table test
2109
2110 # Did we encounter this template already? If yes, it is in the cache
2111 # and we need to check for loops.
2112 if ( !$found && isset( $this->mTemplates[$part1] ) ) {
2113 $found = true;
2114
2115 # Infinite loop test
2116 if ( isset( $this->mTemplatePath[$part1] ) ) {
2117 $noparse = true;
2118 $found = true;
2119 $text = $linestart .
2120 "\{\{$part1}}" .
2121 '<!-- WARNING: template loop detected -->';
2122 wfDebug( "$fname: template loop broken at '$part1'\n" );
2123 } else {
2124 # set $text to cached message.
2125 $text = $linestart . $this->mTemplates[$part1];
2126 }
2127 }
2128
2129 # Load from database
2130 $itcamefromthedatabase = false;
2131 $lastPathLevel = $this->mTemplatePath;
2132 if ( !$found ) {
2133 $ns = NS_TEMPLATE;
2134 $part1 = $this->maybeDoSubpageLink( $part1, $subpage='' );
2135 if ($subpage !== '') {
2136 $ns = $this->mTitle->getNamespace();
2137 }
2138 $title = Title::newFromText( $part1, $ns );
2139 if ( !is_null( $title ) && !$title->isExternal() ) {
2140 # Check for excessive inclusion
2141 $dbk = $title->getPrefixedDBkey();
2142 if ( $this->incrementIncludeCount( $dbk ) ) {
2143 # This should never be reached.
2144 $article = new Article( $title );
2145 $articleContent = $article->getContentWithoutUsingSoManyDamnGlobals();
2146 if ( $articleContent !== false ) {
2147 $found = true;
2148 $text = $linestart . $articleContent;
2149 $itcamefromthedatabase = true;
2150 }
2151 }
2152
2153 # If the title is valid but undisplayable, make a link to it
2154 if ( $this->mOutputType == OT_HTML && !$found ) {
2155 $text = $linestart . '[['.$title->getPrefixedText().']]';
2156 $found = true;
2157 }
2158
2159 # Template cache array insertion
2160 if( $found ) {
2161 $this->mTemplates[$part1] = $text;
2162 }
2163 }
2164 }
2165
2166 # Recursive parsing, escaping and link table handling
2167 # Only for HTML output
2168 if ( $nowiki && $found && $this->mOutputType == OT_HTML ) {
2169 $text = wfEscapeWikiText( $text );
2170 } elseif ( ($this->mOutputType == OT_HTML || $this->mOutputType == OT_WIKI) && $found && !$noparse) {
2171 # Clean up argument array
2172 $assocArgs = array();
2173 $index = 1;
2174 foreach( $args as $arg ) {
2175 $eqpos = strpos( $arg, '=' );
2176 if ( $eqpos === false ) {
2177 $assocArgs[$index++] = $arg;
2178 } else {
2179 $name = trim( substr( $arg, 0, $eqpos ) );
2180 $value = trim( substr( $arg, $eqpos+1 ) );
2181 if ( $value === false ) {
2182 $value = '';
2183 }
2184 if ( $name !== false ) {
2185 $assocArgs[$name] = $value;
2186 }
2187 }
2188 }
2189
2190 # Add a new element to the templace recursion path
2191 $this->mTemplatePath[$part1] = 1;
2192
2193 if( $this->mOutputType == OT_HTML ) {
2194 $text = $this->strip( $text, $this->mStripState );
2195 $text = Sanitizer::removeHTMLtags( $text );
2196 }
2197 $text = $this->replaceVariables( $text, $assocArgs );
2198
2199 # Resume the link cache and register the inclusion as a link
2200 if ( $this->mOutputType == OT_HTML && !is_null( $title ) ) {
2201 $wgLinkCache->addLinkObj( $title );
2202 }
2203
2204 # If the template begins with a table or block-level
2205 # element, it should be treated as beginning a new line.
2206 if ($linestart !== '\n' && preg_match('/^({\\||:|;|#|\*)/', $text)) {
2207 $text = "\n" . $text;
2208 }
2209 }
2210 # Prune lower levels off the recursion check path
2211 $this->mTemplatePath = $lastPathLevel;
2212
2213 if ( !$found ) {
2214 wfProfileOut( $fname );
2215 return $matches[0];
2216 } else {
2217 # replace ==section headers==
2218 # XXX this needs to go away once we have a better parser.
2219 if ( $this->mOutputType != OT_WIKI && $itcamefromthedatabase ) {
2220 if( !is_null( $title ) )
2221 $encodedname = base64_encode($title->getPrefixedDBkey());
2222 else
2223 $encodedname = base64_encode("");
2224 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
2225 PREG_SPLIT_DELIM_CAPTURE);
2226 $text = '';
2227 $nsec = 0;
2228 for( $i = 0; $i < count($m); $i += 2 ) {
2229 $text .= $m[$i];
2230 if (!isset($m[$i + 1]) || $m[$i + 1] == "") continue;
2231 $hl = $m[$i + 1];
2232 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
2233 $text .= $hl;
2234 continue;
2235 }
2236 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
2237 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
2238 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
2239
2240 $nsec++;
2241 }
2242 }
2243 }
2244 # Prune lower levels off the recursion check path
2245 $this->mTemplatePath = $lastPathLevel;
2246
2247 if ( !$found ) {
2248 wfProfileOut( $fname );
2249 return $matches[0];
2250 } else {
2251 wfProfileOut( $fname );
2252 return $text;
2253 }
2254 }
2255
2256 /**
2257 * Triple brace replacement -- used for template arguments
2258 * @access private
2259 */
2260 function argSubstitution( $matches ) {
2261 $arg = trim( $matches[1] );
2262 $text = $matches[0];
2263 $inputArgs = end( $this->mArgStack );
2264
2265 if ( array_key_exists( $arg, $inputArgs ) ) {
2266 $text = $inputArgs[$arg];
2267 }
2268
2269 return $text;
2270 }
2271
2272 /**
2273 * Returns true if the function is allowed to include this entity
2274 * @access private
2275 */
2276 function incrementIncludeCount( $dbk ) {
2277 if ( !array_key_exists( $dbk, $this->mIncludeCount ) ) {
2278 $this->mIncludeCount[$dbk] = 0;
2279 }
2280 if ( ++$this->mIncludeCount[$dbk] <= MAX_INCLUDE_REPEAT ) {
2281 return true;
2282 } else {
2283 return false;
2284 }
2285 }
2286
2287 /**
2288 * This function accomplishes several tasks:
2289 * 1) Auto-number headings if that option is enabled
2290 * 2) Add an [edit] link to sections for logged in users who have enabled the option
2291 * 3) Add a Table of contents on the top for users who have enabled the option
2292 * 4) Auto-anchor headings
2293 *
2294 * It loops through all headlines, collects the necessary data, then splits up the
2295 * string and re-inserts the newly formatted headlines.
2296 *
2297 * @param string $text
2298 * @param boolean $isMain
2299 * @access private
2300 */
2301 function formatHeadings( $text, $isMain=true ) {
2302 global $wgInputEncoding, $wgMaxTocLevel, $wgContLang, $wgLinkHolders, $wgInterwikiLinkHolders;
2303
2304 $doNumberHeadings = $this->mOptions->getNumberHeadings();
2305 $doShowToc = true;
2306 $forceTocHere = false;
2307 if( !$this->mTitle->userCanEdit() ) {
2308 $showEditLink = 0;
2309 } else {
2310 $showEditLink = $this->mOptions->getEditSection();
2311 }
2312
2313 # Inhibit editsection links if requested in the page
2314 $esw =& MagicWord::get( MAG_NOEDITSECTION );
2315 if( $esw->matchAndRemove( $text ) ) {
2316 $showEditLink = 0;
2317 }
2318 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
2319 # do not add TOC
2320 $mw =& MagicWord::get( MAG_NOTOC );
2321 if( $mw->matchAndRemove( $text ) ) {
2322 $doShowToc = false;
2323 }
2324
2325 # Get all headlines for numbering them and adding funky stuff like [edit]
2326 # links - this is for later, but we need the number of headlines right now
2327 $numMatches = preg_match_all( '/<H([1-6])(.*?'.'>)(.*?)<\/H[1-6] *>/i', $text, $matches );
2328
2329 # if there are fewer than 4 headlines in the article, do not show TOC
2330 if( $numMatches < 4 ) {
2331 $doShowToc = false;
2332 }
2333
2334 # if the string __TOC__ (not case-sensitive) occurs in the HTML,
2335 # override above conditions and always show TOC at that place
2336
2337 $mw =& MagicWord::get( MAG_TOC );
2338 if($mw->match( $text ) ) {
2339 $doShowToc = true;
2340 $forceTocHere = true;
2341 } else {
2342 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
2343 # override above conditions and always show TOC above first header
2344 $mw =& MagicWord::get( MAG_FORCETOC );
2345 if ($mw->matchAndRemove( $text ) ) {
2346 $doShowToc = true;
2347 }
2348 }
2349
2350 # Never ever show TOC if no headers
2351 if( $numMatches < 1 ) {
2352 $doShowToc = false;
2353 }
2354
2355 # We need this to perform operations on the HTML
2356 $sk =& $this->mOptions->getSkin();
2357
2358 # headline counter
2359 $headlineCount = 0;
2360 $sectionCount = 0; # headlineCount excluding template sections
2361
2362 # Ugh .. the TOC should have neat indentation levels which can be
2363 # passed to the skin functions. These are determined here
2364 $toc = '';
2365 $full = '';
2366 $head = array();
2367 $sublevelCount = array();
2368 $levelCount = array();
2369 $toclevel = 0;
2370 $level = 0;
2371 $prevlevel = 0;
2372 $toclevel = 0;
2373 $prevtoclevel = 0;
2374
2375 foreach( $matches[3] as $headline ) {
2376 $istemplate = 0;
2377 $templatetitle = '';
2378 $templatesection = 0;
2379 $numbering = '';
2380
2381 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
2382 $istemplate = 1;
2383 $templatetitle = base64_decode($mat[1]);
2384 $templatesection = 1 + (int)base64_decode($mat[2]);
2385 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
2386 }
2387
2388 if( $toclevel ) {
2389 $prevlevel = $level;
2390 $prevtoclevel = $toclevel;
2391 }
2392 $level = $matches[1][$headlineCount];
2393
2394 if( $doNumberHeadings || $doShowToc ) {
2395
2396 if ( $level > $prevlevel ) {
2397 # Increase TOC level
2398 $toclevel++;
2399 $sublevelCount[$toclevel] = 0;
2400 $toc .= $sk->tocIndent();
2401 }
2402 elseif ( $level < $prevlevel && $toclevel > 1 ) {
2403 # Decrease TOC level, find level to jump to
2404
2405 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
2406 # Can only go down to level 1
2407 $toclevel = 1;
2408 } else {
2409 for ($i = $toclevel; $i > 0; $i--) {
2410 if ( $levelCount[$i] == $level ) {
2411 # Found last matching level
2412 $toclevel = $i;
2413 break;
2414 }
2415 elseif ( $levelCount[$i] < $level ) {
2416 # Found first matching level below current level
2417 $toclevel = $i + 1;
2418 break;
2419 }
2420 }
2421 }
2422
2423 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
2424 }
2425 else {
2426 # No change in level, end TOC line
2427 $toc .= $sk->tocLineEnd();
2428 }
2429
2430 $levelCount[$toclevel] = $level;
2431
2432 # count number of headlines for each level
2433 @$sublevelCount[$toclevel]++;
2434 $dot = 0;
2435 for( $i = 1; $i <= $toclevel; $i++ ) {
2436 if( !empty( $sublevelCount[$i] ) ) {
2437 if( $dot ) {
2438 $numbering .= '.';
2439 }
2440 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
2441 $dot = 1;
2442 }
2443 }
2444 }
2445
2446 # The canonized header is a version of the header text safe to use for links
2447 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
2448 $canonized_headline = $this->unstrip( $headline, $this->mStripState );
2449 $canonized_headline = $this->unstripNoWiki( $canonized_headline, $this->mStripState );
2450
2451 # Remove link placeholders by the link text.
2452 # <!--LINK number-->
2453 # turns into
2454 # link text with suffix
2455 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
2456 "\$this->mLinkHolders['texts'][\$1]",
2457 $canonized_headline );
2458 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
2459 "\$this->mInterwikiLinkHolders[\$1][1]",
2460 $canonized_headline );
2461
2462 # strip out HTML
2463 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
2464 $tocline = trim( $canonized_headline );
2465 $canonized_headline = urlencode( do_html_entity_decode( str_replace(' ', '_', $tocline), ENT_COMPAT, $wgInputEncoding ) );
2466 $replacearray = array(
2467 '%3A' => ':',
2468 '%' => '.'
2469 );
2470 $canonized_headline = str_replace(array_keys($replacearray),array_values($replacearray),$canonized_headline);
2471 $refers[$headlineCount] = $canonized_headline;
2472
2473 # count how many in assoc. array so we can track dupes in anchors
2474 @$refers[$canonized_headline]++;
2475 $refcount[$headlineCount]=$refers[$canonized_headline];
2476
2477 # Don't number the heading if it is the only one (looks silly)
2478 if( $doNumberHeadings && count( $matches[3] ) > 1) {
2479 # the two are different if the line contains a link
2480 $headline=$numbering . ' ' . $headline;
2481 }
2482
2483 # Create the anchor for linking from the TOC to the section
2484 $anchor = $canonized_headline;
2485 if($refcount[$headlineCount] > 1 ) {
2486 $anchor .= '_' . $refcount[$headlineCount];
2487 }
2488 if( $doShowToc && ( !isset($wgMaxTocLevel) || $toclevel<$wgMaxTocLevel ) ) {
2489 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
2490 }
2491 if( $showEditLink && ( !$istemplate || $templatetitle !== "" ) ) {
2492 if ( empty( $head[$headlineCount] ) ) {
2493 $head[$headlineCount] = '';
2494 }
2495 if( $istemplate )
2496 $head[$headlineCount] .= $sk->editSectionLinkForOther($templatetitle, $templatesection);
2497 else
2498 $head[$headlineCount] .= $sk->editSectionLink($this->mTitle, $sectionCount+1);
2499 }
2500
2501 # give headline the correct <h#> tag
2502 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline.'</h'.$level.'>';
2503
2504 $headlineCount++;
2505 if( !$istemplate )
2506 $sectionCount++;
2507 }
2508
2509 if( $doShowToc ) {
2510 $toc .= $sk->tocUnindent( $toclevel - 1 );
2511 $toc = $sk->tocList( $toc );
2512 }
2513
2514 # split up and insert constructed headlines
2515
2516 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
2517 $i = 0;
2518
2519 foreach( $blocks as $block ) {
2520 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
2521 # This is the [edit] link that appears for the top block of text when
2522 # section editing is enabled
2523
2524 # Disabled because it broke block formatting
2525 # For example, a bullet point in the top line
2526 # $full .= $sk->editSectionLink(0);
2527 }
2528 $full .= $block;
2529 if( $doShowToc && !$i && $isMain && !$forceTocHere) {
2530 # Top anchor now in skin
2531 $full = $full.$toc;
2532 }
2533
2534 if( !empty( $head[$i] ) ) {
2535 $full .= $head[$i];
2536 }
2537 $i++;
2538 }
2539 if($forceTocHere) {
2540 $mw =& MagicWord::get( MAG_TOC );
2541 return $mw->replace( $toc, $full );
2542 } else {
2543 return $full;
2544 }
2545 }
2546
2547 /**
2548 * Return an HTML link for the "ISBN 123456" text
2549 * @access private
2550 */
2551 function magicISBN( $text ) {
2552 $fname = 'Parser::magicISBN';
2553 wfProfileIn( $fname );
2554
2555 $a = split( 'ISBN ', ' '.$text );
2556 if ( count ( $a ) < 2 ) {
2557 wfProfileOut( $fname );
2558 return $text;
2559 }
2560 $text = substr( array_shift( $a ), 1);
2561 $valid = '0123456789-Xx';
2562
2563 foreach ( $a as $x ) {
2564 $isbn = $blank = '' ;
2565 while ( ' ' == $x{0} ) {
2566 $blank .= ' ';
2567 $x = substr( $x, 1 );
2568 }
2569 if ( $x == '' ) { # blank isbn
2570 $text .= "ISBN $blank";
2571 continue;
2572 }
2573 while ( strstr( $valid, $x{0} ) != false ) {
2574 $isbn .= $x{0};
2575 $x = substr( $x, 1 );
2576 }
2577 $num = str_replace( '-', '', $isbn );
2578 $num = str_replace( ' ', '', $num );
2579 $num = str_replace( 'x', 'X', $num );
2580
2581 if ( '' == $num ) {
2582 $text .= "ISBN $blank$x";
2583 } else {
2584 $titleObj = Title::makeTitle( NS_SPECIAL, 'Booksources' );
2585 $text .= '<a href="' .
2586 $titleObj->escapeLocalUrl( 'isbn='.$num ) .
2587 "\" class=\"internal\">ISBN $isbn</a>";
2588 $text .= $x;
2589 }
2590 }
2591 wfProfileOut( $fname );
2592 return $text;
2593 }
2594
2595 /**
2596 * Return an HTML link for the "RFC 1234" text
2597 *
2598 * @access private
2599 * @param string $text Text to be processed
2600 * @param string $keyword Magic keyword to use (default RFC)
2601 * @param string $urlmsg Interface message to use (default rfcurl)
2602 * @return string
2603 */
2604 function magicRFC( $text, $keyword='RFC ', $urlmsg='rfcurl' ) {
2605
2606 $valid = '0123456789';
2607 $internal = false;
2608
2609 $a = split( $keyword, ' '.$text );
2610 if ( count ( $a ) < 2 ) {
2611 return $text;
2612 }
2613 $text = substr( array_shift( $a ), 1);
2614
2615 /* Check if keyword is preceed by [[.
2616 * This test is made here cause of the array_shift above
2617 * that prevent the test to be done in the foreach.
2618 */
2619 if ( substr( $text, -2 ) == '[[' ) {
2620 $internal = true;
2621 }
2622
2623 foreach ( $a as $x ) {
2624 /* token might be empty if we have RFC RFC 1234 */
2625 if ( $x=='' ) {
2626 $text.=$keyword;
2627 continue;
2628 }
2629
2630 $id = $blank = '' ;
2631
2632 /** remove and save whitespaces in $blank */
2633 while ( $x{0} == ' ' ) {
2634 $blank .= ' ';
2635 $x = substr( $x, 1 );
2636 }
2637
2638 /** remove and save the rfc number in $id */
2639 while ( strstr( $valid, $x{0} ) != false ) {
2640 $id .= $x{0};
2641 $x = substr( $x, 1 );
2642 }
2643
2644 if ( $id == '' ) {
2645 /* call back stripped spaces*/
2646 $text .= $keyword.$blank.$x;
2647 } elseif( $internal ) {
2648 /* normal link */
2649 $text .= $keyword.$id.$x;
2650 } else {
2651 /* build the external link*/
2652 $url = wfMsg( $urlmsg, $id);
2653 $sk =& $this->mOptions->getSkin();
2654 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
2655 $text .= "<a href='{$url}'{$la}>{$keyword}{$id}</a>{$x}";
2656 }
2657
2658 /* Check if the next RFC keyword is preceed by [[ */
2659 $internal = ( substr($x,-2) == '[[' );
2660 }
2661 return $text;
2662 }
2663
2664 /**
2665 * Transform wiki markup when saving a page by doing \r\n -> \n
2666 * conversion, substitting signatures, {{subst:}} templates, etc.
2667 *
2668 * @param string $text the text to transform
2669 * @param Title &$title the Title object for the current article
2670 * @param User &$user the User object describing the current user
2671 * @param ParserOptions $options parsing options
2672 * @param bool $clearState whether to clear the parser state first
2673 * @return string the altered wiki markup
2674 * @access public
2675 */
2676 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true ) {
2677 $this->mOptions = $options;
2678 $this->mTitle =& $title;
2679 $this->mOutputType = OT_WIKI;
2680
2681 if ( $clearState ) {
2682 $this->clearState();
2683 }
2684
2685 $stripState = false;
2686 $pairs = array(
2687 "\r\n" => "\n",
2688 );
2689 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
2690 $text = $this->strip( $text, $stripState, false );
2691 $text = $this->pstPass2( $text, $user );
2692 $text = $this->unstrip( $text, $stripState );
2693 $text = $this->unstripNoWiki( $text, $stripState );
2694 return $text;
2695 }
2696
2697 /**
2698 * Pre-save transform helper function
2699 * @access private
2700 */
2701 function pstPass2( $text, &$user ) {
2702 global $wgContLang, $wgLocaltimezone;
2703
2704 # Variable replacement
2705 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
2706 $text = $this->replaceVariables( $text );
2707
2708 # Signatures
2709 #
2710 $n = $user->getName();
2711 $k = $user->getOption( 'nickname' );
2712 if ( '' == $k ) { $k = $n; }
2713 if ( isset( $wgLocaltimezone ) ) {
2714 $oldtz = getenv( 'TZ' );
2715 putenv( 'TZ='.$wgLocaltimezone );
2716 }
2717
2718 /* Note: This is the timestamp saved as hardcoded wikitext to
2719 * the database, we use $wgContLang here in order to give
2720 * everyone the same signiture and use the default one rather
2721 * than the one selected in each users preferences.
2722 */
2723 $d = $wgContLang->timeanddate( wfTimestampNow(), false, false) .
2724 ' (' . date( 'T' ) . ')';
2725 if ( isset( $wgLocaltimezone ) ) {
2726 putenv( 'TZ='.$oldtz );
2727 }
2728
2729 if( $user->getOption( 'fancysig' ) ) {
2730 $sigText = $k;
2731 } else {
2732 $sigText = '[[' . $wgContLang->getNsText( NS_USER ) . ":$n|$k]]";
2733 }
2734 $text = preg_replace( '/~~~~~/', $d, $text );
2735 $text = preg_replace( '/~~~~/', "$sigText $d", $text );
2736 $text = preg_replace( '/~~~/', $sigText, $text );
2737
2738 # Context links: [[|name]] and [[name (context)|]]
2739 #
2740 $tc = "[&;%\\-,.\\(\\)' _0-9A-Za-z\\/:\\x80-\\xff]";
2741 $np = "[&;%\\-,.' _0-9A-Za-z\\/:\\x80-\\xff]"; # No parens
2742 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
2743 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
2744
2745 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
2746 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
2747 $p3 = "/\[\[(:*$namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]] and [[:namespace:page|]]
2748 $p4 = "/\[\[(:*$namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/"; # [[ns:page (cont)|]] and [[:ns:page (cont)|]]
2749 $context = '';
2750 $t = $this->mTitle->getText();
2751 if ( preg_match( $conpat, $t, $m ) ) {
2752 $context = $m[2];
2753 }
2754 $text = preg_replace( $p4, '[[\\1:\\2 (\\3)|\\2]]', $text );
2755 $text = preg_replace( $p1, '[[\\1 (\\2)|\\1]]', $text );
2756 $text = preg_replace( $p3, '[[\\1:\\2|\\2]]', $text );
2757
2758 if ( '' == $context ) {
2759 $text = preg_replace( $p2, '[[\\1]]', $text );
2760 } else {
2761 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
2762 }
2763
2764 # Trim trailing whitespace
2765 # MAG_END (__END__) tag allows for trailing
2766 # whitespace to be deliberately included
2767 $text = rtrim( $text );
2768 $mw =& MagicWord::get( MAG_END );
2769 $mw->matchAndRemove( $text );
2770
2771 return $text;
2772 }
2773
2774 /**
2775 * Set up some variables which are usually set up in parse()
2776 * so that an external function can call some class members with confidence
2777 * @access public
2778 */
2779 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
2780 $this->mTitle =& $title;
2781 $this->mOptions = $options;
2782 $this->mOutputType = $outputType;
2783 if ( $clearState ) {
2784 $this->clearState();
2785 }
2786 }
2787
2788 /**
2789 * Transform a MediaWiki message by replacing magic variables.
2790 *
2791 * @param string $text the text to transform
2792 * @param ParserOptions $options options
2793 * @return string the text with variables substituted
2794 * @access public
2795 */
2796 function transformMsg( $text, $options ) {
2797 global $wgTitle;
2798 static $executing = false;
2799
2800 # Guard against infinite recursion
2801 if ( $executing ) {
2802 return $text;
2803 }
2804 $executing = true;
2805
2806 $this->mTitle = $wgTitle;
2807 $this->mOptions = $options;
2808 $this->mOutputType = OT_MSG;
2809 $this->clearState();
2810 $text = $this->replaceVariables( $text );
2811
2812 $executing = false;
2813 return $text;
2814 }
2815
2816 /**
2817 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
2818 * Callback will be called with the text within
2819 * Transform and return the text within
2820 * @access public
2821 */
2822 function setHook( $tag, $callback ) {
2823 $oldVal = @$this->mTagHooks[$tag];
2824 $this->mTagHooks[$tag] = $callback;
2825 return $oldVal;
2826 }
2827
2828 /**
2829 * Replace <!--LINK--> link placeholders with actual links, in the buffer
2830 * Placeholders created in Skin::makeLinkObj()
2831 * Returns an array of links found, indexed by PDBK:
2832 * 0 - broken
2833 * 1 - normal link
2834 * 2 - stub
2835 * $options is a bit field, RLH_FOR_UPDATE to select for update
2836 */
2837 function replaceLinkHolders( &$text, $options = 0 ) {
2838 global $wgUser, $wgLinkCache;
2839 global $wgOutputReplace;
2840
2841 $fname = 'Parser::replaceLinkHolders';
2842 wfProfileIn( $fname );
2843
2844 $pdbks = array();
2845 $colours = array();
2846 $sk = $this->mOptions->getSkin();
2847
2848 if ( !empty( $this->mLinkHolders['namespaces'] ) ) {
2849 wfProfileIn( $fname.'-check' );
2850 $dbr =& wfGetDB( DB_SLAVE );
2851 $page = $dbr->tableName( 'page' );
2852 $threshold = $wgUser->getOption('stubthreshold');
2853
2854 # Sort by namespace
2855 asort( $this->mLinkHolders['namespaces'] );
2856
2857 # Generate query
2858 $query = false;
2859 foreach ( $this->mLinkHolders['namespaces'] as $key => $val ) {
2860 # Make title object
2861 $title = $this->mLinkHolders['titles'][$key];
2862
2863 # Skip invalid entries.
2864 # Result will be ugly, but prevents crash.
2865 if ( is_null( $title ) ) {
2866 continue;
2867 }
2868 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
2869
2870 # Check if it's in the link cache already
2871 if ( $wgLinkCache->getGoodLinkID( $pdbk ) ) {
2872 $colours[$pdbk] = 1;
2873 } elseif ( $wgLinkCache->isBadLink( $pdbk ) ) {
2874 $colours[$pdbk] = 0;
2875 } else {
2876 # Not in the link cache, add it to the query
2877 if ( !isset( $current ) ) {
2878 $current = $val;
2879 $query = "SELECT page_id, page_namespace, page_title";
2880 if ( $threshold > 0 ) {
2881 $query .= ', page_len, page_is_redirect';
2882 }
2883 $query .= " FROM $page WHERE (page_namespace=$val AND page_title IN(";
2884 } elseif ( $current != $val ) {
2885 $current = $val;
2886 $query .= ")) OR (page_namespace=$val AND page_title IN(";
2887 } else {
2888 $query .= ', ';
2889 }
2890
2891 $query .= $dbr->addQuotes( $this->mLinkHolders['dbkeys'][$key] );
2892 }
2893 }
2894 if ( $query ) {
2895 $query .= '))';
2896 if ( $options & RLH_FOR_UPDATE ) {
2897 $query .= ' FOR UPDATE';
2898 }
2899
2900 $res = $dbr->query( $query, $fname );
2901
2902 # Fetch data and form into an associative array
2903 # non-existent = broken
2904 # 1 = known
2905 # 2 = stub
2906 while ( $s = $dbr->fetchObject($res) ) {
2907 $title = Title::makeTitle( $s->page_namespace, $s->page_title );
2908 $pdbk = $title->getPrefixedDBkey();
2909 $wgLinkCache->addGoodLink( $s->page_id, $pdbk );
2910
2911 if ( $threshold > 0 ) {
2912 $size = $s->page_len;
2913 if ( $s->page_is_redirect || $s->page_namespace != 0 || $size >= $threshold ) {
2914 $colours[$pdbk] = 1;
2915 } else {
2916 $colours[$pdbk] = 2;
2917 }
2918 } else {
2919 $colours[$pdbk] = 1;
2920 }
2921 }
2922 }
2923 wfProfileOut( $fname.'-check' );
2924
2925 # Construct search and replace arrays
2926 wfProfileIn( $fname.'-construct' );
2927 $wgOutputReplace = array();
2928 foreach ( $this->mLinkHolders['namespaces'] as $key => $ns ) {
2929 $pdbk = $pdbks[$key];
2930 $searchkey = "<!--LINK $key-->";
2931 $title = $this->mLinkHolders['titles'][$key];
2932 if ( empty( $colours[$pdbk] ) ) {
2933 $wgLinkCache->addBadLink( $pdbk );
2934 $colours[$pdbk] = 0;
2935 $wgOutputReplace[$searchkey] = $sk->makeBrokenLinkObj( $title,
2936 $this->mLinkHolders['texts'][$key],
2937 $this->mLinkHolders['queries'][$key] );
2938 } elseif ( $colours[$pdbk] == 1 ) {
2939 $wgOutputReplace[$searchkey] = $sk->makeKnownLinkObj( $title,
2940 $this->mLinkHolders['texts'][$key],
2941 $this->mLinkHolders['queries'][$key] );
2942 } elseif ( $colours[$pdbk] == 2 ) {
2943 $wgOutputReplace[$searchkey] = $sk->makeStubLinkObj( $title,
2944 $this->mLinkHolders['texts'][$key],
2945 $this->mLinkHolders['queries'][$key] );
2946 }
2947 }
2948 wfProfileOut( $fname.'-construct' );
2949
2950 # Do the thing
2951 wfProfileIn( $fname.'-replace' );
2952
2953 $text = preg_replace_callback(
2954 '/(<!--LINK .*?-->)/',
2955 "wfOutputReplaceMatches",
2956 $text);
2957
2958 wfProfileOut( $fname.'-replace' );
2959 }
2960
2961 # Now process interwiki link holders
2962 # This is quite a bit simpler than internal links
2963 if ( !empty( $this->mInterwikiLinkHolders ) ) {
2964 wfProfileIn( $fname.'-interwiki' );
2965 # Make interwiki link HTML
2966 $wgOutputReplace = array();
2967 foreach( $this->mInterwikiLinkHolders as $i => $lh ) {
2968 $s = $sk->makeLink( $lh[0], $lh[1] );
2969 $wgOutputReplace[] = $s;
2970 }
2971
2972 $text = preg_replace_callback(
2973 '/<!--IWLINK (.*?)-->/',
2974 "wfOutputReplaceMatches",
2975 $text );
2976 wfProfileOut( $fname.'-interwiki' );
2977 }
2978
2979 wfProfileOut( $fname );
2980 return $colours;
2981 }
2982
2983 /**
2984 * Renders an image gallery from a text with one line per image.
2985 * text labels may be given by using |-style alternative text. E.g.
2986 * Image:one.jpg|The number "1"
2987 * Image:tree.jpg|A tree
2988 * given as text will return the HTML of a gallery with two images,
2989 * labeled 'The number "1"' and
2990 * 'A tree'.
2991 *
2992 * @static
2993 */
2994 function renderImageGallery( $text ) {
2995 # Setup the parser
2996 global $wgUser, $wgParser, $wgTitle;
2997 $parserOptions = ParserOptions::newFromUser( $wgUser );
2998
2999 global $wgLinkCache;
3000 $ig = new ImageGallery();
3001 $ig->setShowBytes( false );
3002 $ig->setShowFilename( false );
3003 $lines = explode( "\n", $text );
3004
3005 foreach ( $lines as $line ) {
3006 # match lines like these:
3007 # Image:someimage.jpg|This is some image
3008 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
3009 # Skip empty lines
3010 if ( count( $matches ) == 0 ) {
3011 continue;
3012 }
3013 $nt = Title::newFromURL( $matches[1] );
3014 if( is_null( $nt ) ) {
3015 # Bogus title. Ignore these so we don't bomb out later.
3016 continue;
3017 }
3018 if ( isset( $matches[3] ) ) {
3019 $label = $matches[3];
3020 } else {
3021 $label = '';
3022 }
3023
3024 $html = $wgParser->parse( $label , $wgTitle, $parserOptions );
3025 $html = $html->mText;
3026
3027 $ig->add( new Image( $nt ), $html );
3028 $wgLinkCache->addImageLinkObj( $nt );
3029 }
3030 return $ig->toHTML();
3031 }
3032
3033 /**
3034 * Parse image options text and use it to make an image
3035 */
3036 function makeImage( &$nt, $options ) {
3037 global $wgContLang, $wgUseImageResize;
3038 global $wgUser, $wgThumbLimits;
3039
3040 $align = '';
3041
3042 # Check if the options text is of the form "options|alt text"
3043 # Options are:
3044 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
3045 # * left no resizing, just left align. label is used for alt= only
3046 # * right same, but right aligned
3047 # * none same, but not aligned
3048 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
3049 # * center center the image
3050 # * framed Keep original image size, no magnify-button.
3051
3052 $part = explode( '|', $options);
3053
3054 $mwThumb =& MagicWord::get( MAG_IMG_THUMBNAIL );
3055 $mwLeft =& MagicWord::get( MAG_IMG_LEFT );
3056 $mwRight =& MagicWord::get( MAG_IMG_RIGHT );
3057 $mwNone =& MagicWord::get( MAG_IMG_NONE );
3058 $mwWidth =& MagicWord::get( MAG_IMG_WIDTH );
3059 $mwCenter =& MagicWord::get( MAG_IMG_CENTER );
3060 $mwFramed =& MagicWord::get( MAG_IMG_FRAMED );
3061 $caption = '';
3062
3063 $width = $height = $framed = $thumb = false;
3064 $manual_thumb = "" ;
3065
3066 foreach( $part as $key => $val ) {
3067 $val_parts = explode ( "=" , $val , 2 ) ;
3068 $left_part = array_shift ( $val_parts ) ;
3069 if ( $wgUseImageResize && ! is_null( $mwThumb->matchVariableStartToEnd($val) ) ) {
3070 $thumb=true;
3071 } elseif ( $wgUseImageResize && count ( $val_parts ) == 1 && ! is_null( $mwThumb->matchVariableStartToEnd($left_part) ) ) {
3072 # use manually specified thumbnail
3073 $thumb=true;
3074 $manual_thumb = array_shift ( $val_parts ) ;
3075 } elseif ( ! is_null( $mwRight->matchVariableStartToEnd($val) ) ) {
3076 # remember to set an alignment, don't render immediately
3077 $align = 'right';
3078 } elseif ( ! is_null( $mwLeft->matchVariableStartToEnd($val) ) ) {
3079 # remember to set an alignment, don't render immediately
3080 $align = 'left';
3081 } elseif ( ! is_null( $mwCenter->matchVariableStartToEnd($val) ) ) {
3082 # remember to set an alignment, don't render immediately
3083 $align = 'center';
3084 } elseif ( ! is_null( $mwNone->matchVariableStartToEnd($val) ) ) {
3085 # remember to set an alignment, don't render immediately
3086 $align = 'none';
3087 } elseif ( $wgUseImageResize && ! is_null( $match = $mwWidth->matchVariableStartToEnd($val) ) ) {
3088 wfDebug( "MAG_IMG_WIDTH match: $match\n" );
3089 # $match is the image width in pixels
3090 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $match, $m ) ) {
3091 $width = intval( $m[1] );
3092 $height = intval( $m[2] );
3093 } else {
3094 $width = intval($match);
3095 }
3096 } elseif ( ! is_null( $mwFramed->matchVariableStartToEnd($val) ) ) {
3097 $framed=true;
3098 } else {
3099 $caption = $val;
3100 }
3101 }
3102 # Strip bad stuff out of the alt text
3103 $alt = $caption;
3104 $this->replaceLinkHolders( $alt );
3105 $alt = Sanitizer::stripAllTags( $alt );
3106
3107 # Linker does the rest
3108 $sk =& $this->mOptions->getSkin();
3109 return $sk->makeImageLinkObj( $nt, $caption, $alt, $align, $width, $height, $framed, $thumb, $manual_thumb );
3110 }
3111 }
3112
3113 /**
3114 * @todo document
3115 * @package MediaWiki
3116 */
3117 class ParserOutput
3118 {
3119 var $mText, $mLanguageLinks, $mCategoryLinks, $mContainsOldMagic;
3120 var $mCacheTime; # Used in ParserCache
3121 var $mVersion; # Compatibility check
3122 var $mTitleText; # title text of the chosen language variant
3123 var $mLcfirstTitle; # This is true if the first letter in the title has to be lowercase
3124
3125 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
3126 $containsOldMagic = false, $titletext = '' )
3127 {
3128 $this->mText = $text;
3129 $this->mLanguageLinks = $languageLinks;
3130 $this->mCategoryLinks = $categoryLinks;
3131 $this->mContainsOldMagic = $containsOldMagic;
3132 $this->mCacheTime = '';
3133 $this->mVersion = MW_PARSER_VERSION;
3134 $this->mTitleText = $titletext;
3135 }
3136
3137 function getText() { return $this->mText; }
3138 function getLanguageLinks() { return $this->mLanguageLinks; }
3139 function getCategoryLinks() { return array_keys( $this->mCategoryLinks ); }
3140 function getCacheTime() { return $this->mCacheTime; }
3141 function getTitleText() { return $this->mTitleText; }
3142 function getLcfirstTitle() { return $this->mLcfirstTitle; }
3143 function containsOldMagic() { return $this->mContainsOldMagic; }
3144 function setText( $text ) { return wfSetVar( $this->mText, $text ); }
3145 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks, $ll ); }
3146 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategoryLinks, $cl ); }
3147 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic, $com ); }
3148 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime, $t ); }
3149 function setTitleText( $t ) { return wfSetVar ($this->mTitleText, $t); }
3150
3151 function addCategoryLink( $c ) { $this->mCategoryLinks[$c] = 1; }
3152
3153 function merge( $other ) {
3154 $this->mLanguageLinks = array_merge( $this->mLanguageLinks, $other->mLanguageLinks );
3155 $this->mCategoryLinks = array_merge( $this->mCategoryLinks, $this->mLanguageLinks );
3156 $this->mContainsOldMagic = $this->mContainsOldMagic || $other->mContainsOldMagic;
3157 }
3158
3159 /**
3160 * Return true if this cached output object predates the global or
3161 * per-article cache invalidation timestamps, or if it comes from
3162 * an incompatible older version.
3163 *
3164 * @param string $touched the affected article's last touched timestamp
3165 * @return bool
3166 * @access public
3167 */
3168 function expired( $touched ) {
3169 global $wgCacheEpoch;
3170 return $this->getCacheTime() <= $touched ||
3171 $this->getCacheTime() <= $wgCacheEpoch ||
3172 !isset( $this->mVersion ) ||
3173 version_compare( $this->mVersion, MW_PARSER_VERSION, "lt" );
3174 }
3175 }
3176
3177 /**
3178 * Set options of the Parser
3179 * @todo document
3180 * @package MediaWiki
3181 */
3182 class ParserOptions
3183 {
3184 # All variables are private
3185 var $mUseTeX; # Use texvc to expand <math> tags
3186 var $mUseDynamicDates; # Use DateFormatter to format dates
3187 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
3188 var $mAllowExternalImages; # Allow external images inline
3189 var $mSkin; # Reference to the preferred skin
3190 var $mDateFormat; # Date format index
3191 var $mEditSection; # Create "edit section" links
3192 var $mNumberHeadings; # Automatically number headings
3193
3194 function getUseTeX() { return $this->mUseTeX; }
3195 function getUseDynamicDates() { return $this->mUseDynamicDates; }
3196 function getInterwikiMagic() { return $this->mInterwikiMagic; }
3197 function getAllowExternalImages() { return $this->mAllowExternalImages; }
3198 function getSkin() { return $this->mSkin; }
3199 function getDateFormat() { return $this->mDateFormat; }
3200 function getEditSection() { return $this->mEditSection; }
3201 function getNumberHeadings() { return $this->mNumberHeadings; }
3202
3203 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX, $x ); }
3204 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates, $x ); }
3205 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic, $x ); }
3206 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages, $x ); }
3207 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat, $x ); }
3208 function setEditSection( $x ) { return wfSetVar( $this->mEditSection, $x ); }
3209 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings, $x ); }
3210
3211 function setSkin( &$x ) { $this->mSkin =& $x; }
3212
3213 /**
3214 * Get parser options
3215 * @static
3216 */
3217 function newFromUser( &$user ) {
3218 $popts = new ParserOptions;
3219 $popts->initialiseFromUser( $user );
3220 return $popts;
3221 }
3222
3223 /** Get user options */
3224 function initialiseFromUser( &$userInput ) {
3225 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages;
3226 $fname = 'ParserOptions::initialiseFromUser';
3227 wfProfileIn( $fname );
3228 if ( !$userInput ) {
3229 $user = new User;
3230 $user->setLoaded( true );
3231 } else {
3232 $user =& $userInput;
3233 }
3234
3235 $this->mUseTeX = $wgUseTeX;
3236 $this->mUseDynamicDates = $wgUseDynamicDates;
3237 $this->mInterwikiMagic = $wgInterwikiMagic;
3238 $this->mAllowExternalImages = $wgAllowExternalImages;
3239 wfProfileIn( $fname.'-skin' );
3240 $this->mSkin =& $user->getSkin();
3241 wfProfileOut( $fname.'-skin' );
3242 $this->mDateFormat = $user->getOption( 'date' );
3243 $this->mEditSection = $user->getOption( 'editsection' );
3244 $this->mNumberHeadings = $user->getOption( 'numberheadings' );
3245 wfProfileOut( $fname );
3246 }
3247 }
3248
3249 /**
3250 * Callback function used by Parser::replaceLinkHolders()
3251 * to substitute link placeholders.
3252 */
3253 function &wfOutputReplaceMatches( $matches ) {
3254 global $wgOutputReplace;
3255 return $wgOutputReplace[$matches[1]];
3256 }
3257
3258 /**
3259 * Return the total number of articles
3260 */
3261 function wfNumberOfArticles() {
3262 global $wgNumberOfArticles;
3263
3264 wfLoadSiteStats();
3265 return $wgNumberOfArticles;
3266 }
3267
3268 /**
3269 * Get various statistics from the database
3270 * @private
3271 */
3272 function wfLoadSiteStats() {
3273 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
3274 $fname = 'wfLoadSiteStats';
3275
3276 if ( -1 != $wgNumberOfArticles ) return;
3277 $dbr =& wfGetDB( DB_SLAVE );
3278 $s = $dbr->selectRow( 'site_stats',
3279 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
3280 array( 'ss_row_id' => 1 ), $fname
3281 );
3282
3283 if ( $s === false ) {
3284 return;
3285 } else {
3286 $wgTotalViews = $s->ss_total_views;
3287 $wgTotalEdits = $s->ss_total_edits;
3288 $wgNumberOfArticles = $s->ss_good_articles;
3289 }
3290 }
3291
3292 /**
3293 * Escape html tags
3294 * Basicly replacing " > and < with HTML entities ( &quot;, &gt;, &lt;)
3295 *
3296 * @param string $in Text that might contain HTML tags
3297 * @return string Escaped string
3298 */
3299 function wfEscapeHTMLTagsOnly( $in ) {
3300 return str_replace(
3301 array( '"', '>', '<' ),
3302 array( '&quot;', '&gt;', '&lt;' ),
3303 $in );
3304 }
3305
3306 ?>